mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-22 23:01:41 +03:00
Resolve conflicts from merge
This commit is contained in:
commit
d0b067b140
@ -1,16 +1,18 @@
|
|||||||
# Contributing
|
# Contributing
|
||||||
|
|
||||||
All contributions are welcome, from the tiniest typo to a brand new article. Translations
|
All contributions are welcome, from the tiniest typo to a brand new article.
|
||||||
in all languages are welcome (or, for that matter, original articles in any language).
|
Translations in all languages are welcome (or, for that matter, original
|
||||||
Send a pull request or open an issue any time of day or night.
|
articles in any language). Send a pull request or open an issue any time of day
|
||||||
|
or night.
|
||||||
|
|
||||||
**Please prepend the tag `[language/lang-code]` to your issues and pull requests.** For example,
|
**Please prepend the tag `[language/lang-code]` to your issues and pull
|
||||||
`[python/en]` for English Python. This will help everyone pick out things they care about.
|
requests.** For example, `[python/en]` for English Python. This will help
|
||||||
|
everyone pick out things they care about.
|
||||||
|
|
||||||
We're happy for any contribution in any form, but if you're making more than one major change
|
We're happy for any contribution in any form, but if you're making more than one
|
||||||
(i.e. translations for two different languages) it would be super cool of you to make a
|
major change (i.e. translations for two different languages) it would be super
|
||||||
separate pull request for each one so that someone can review them more effectively and/or
|
cool of you to make a separate pull request for each one so that someone can
|
||||||
individually.
|
review them more effectively and/or individually.
|
||||||
|
|
||||||
## Style Guidelines
|
## Style Guidelines
|
||||||
|
|
||||||
@ -21,28 +23,38 @@ individually.
|
|||||||
+ Try to use as few words as possible.
|
+ Try to use as few words as possible.
|
||||||
+ Code examples are preferred over exposition in all cases.
|
+ Code examples are preferred over exposition in all cases.
|
||||||
- **Eschew surplusage**
|
- **Eschew surplusage**
|
||||||
+ We welcome newcomers, but the target audience for this site is programmers with some experience.
|
+ We welcome newcomers, but the target audience for this site is programmers
|
||||||
+ Try to avoid explaining basic concepts except for those specific to the language in question.
|
with some experience.
|
||||||
|
+ Try to avoid explaining basic concepts except for those specific to the
|
||||||
|
language in question.
|
||||||
+ Keep articles succinct and scannable. We all know how to use Google here.
|
+ Keep articles succinct and scannable. We all know how to use Google here.
|
||||||
- **Use UTF-8**
|
- **Use UTF-8**
|
||||||
+ For translations (or EN articles with non-ASCII characters) please make sure your file is UTF-8 encoded.
|
+ For translations (or EN articles with non-ASCII characters) please make sure
|
||||||
+ Try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in Vim)
|
your file is UTF-8 encoded.
|
||||||
|
+ Try to leave out the byte-order-mark at the start of the file. (`:set nobomb`
|
||||||
|
in Vim)
|
||||||
|
|
||||||
## Header configuration
|
|
||||||
|
|
||||||
The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least
|
### Header configuration
|
||||||
the custom scripts underpinning the site, requires key information to be defined in the header.
|
|
||||||
|
|
||||||
The following fields are necessary for English articles about programming languages:
|
The actual site uses Middleman to generate HTML files from these Markdown ones.
|
||||||
|
Middleman, or at least the custom scripts underpinning the site, requires that
|
||||||
|
some key information be defined in the header.
|
||||||
|
|
||||||
- **language** - The *programming language* in question
|
The following fields are necessary for English articles about programming
|
||||||
- **contributors** - A list of [author, URL] arrays to provide credit
|
languages:
|
||||||
|
|
||||||
|
- **language** The *programming language* in question
|
||||||
|
- **contributors** A list of [author, URL] lists to credit
|
||||||
|
|
||||||
Other fields:
|
Other fields:
|
||||||
|
|
||||||
- **filename** - The filename for this article's code. It will be fetched, mashed together, and made downloadable.
|
- **filename**: The filename for this article's code. It will be fetched, mashed
|
||||||
+ For non-English articles, *filename* should have a language-specific suffix.
|
together, and made downloadable.
|
||||||
- **lang** - For translations, the human language this article is in. For categorization, mostly.
|
+ For non-English articles, *filename* should have a language-specific
|
||||||
|
suffix.
|
||||||
|
- **lang**: For translations, the human language this article is in. For
|
||||||
|
categorization, mostly.
|
||||||
|
|
||||||
Here's an example header for an Esperanto translation of Ruby:
|
Here's an example header for an Esperanto translation of Ruby:
|
||||||
|
|
||||||
|
@ -1,44 +1,45 @@
|
|||||||
# [Learn X in Y minutes][1]
|
# [Learn X in Y minutes][1]
|
||||||
|
|
||||||
Whirlwind tours of (several, hopefully many someday) popular and
|
Whirlwind tours of (several, hopefully many someday) popular and
|
||||||
ought-to-be-more-popular programming languages, presented as valid,
|
ought-to-be-more-popular programming languages, presented as valid, commented
|
||||||
commented code and explained as they go.
|
code and explained as they go.
|
||||||
|
|
||||||
## We need YOU!...
|
## We need YOU!...
|
||||||
|
|
||||||
... to write more inline code tutorials. Just grab an existing file from
|
... to write more inline code tutorials. Just grab an existing file from this
|
||||||
this repo and copy the formatting (don't worry, it's all very simple).
|
repo and copy the formatting (don't worry, it's all very simple). Make a new
|
||||||
Make a new file, send a pull request, and if it passes muster I'll get it up pronto.
|
file, send a pull request, and if it passes muster I'll get it up pronto.
|
||||||
Remember to fill in the "contributors" fields so you get credited
|
Remember to fill in the "contributors" fields so you get credited properly!
|
||||||
properly!
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
All contributions are welcome, from the tiniest typo to a brand new article. Translations
|
All contributions are welcome, from the tiniest typo to a brand new article.
|
||||||
in all languages are welcome (or, for that matter, original articles in any language).
|
Translations in all languages are welcome (or, for that matter, original
|
||||||
Send a pull request or open an issue any time of day or night.
|
articles in any language). Send a pull request or open an issue any time of day
|
||||||
|
or night.
|
||||||
|
|
||||||
**Please prepend the tag `[language/lang-code]` to your issues and pull requests.** For example,
|
**Please prepend the tag `[language/lang-code]` to your issues and pull
|
||||||
`[python/en]` for English Python. This will help everyone pick out things they care about.
|
requests.** For example, `[python/en]` for English Python. This will help
|
||||||
|
everyone pick out things they care about.
|
||||||
|
|
||||||
We're happy for any contribution in any form, but if you're making more than one major change
|
We're happy for any contribution in any form, but if you're making more than one
|
||||||
(i.e. translations for two different languages) it would be super cool of you to make a
|
major change (i.e. translations for two different languages) it would be super
|
||||||
separate pull request for each one so that someone can review them more effectively and/or
|
cool of you to make a separate pull request for each one so that someone can
|
||||||
individually.
|
review them more effectively and/or individually.
|
||||||
|
|
||||||
For a detailed style guide, please review the full [CONTRIBUTING][2] guidelines.
|
For a detailed style guide, please review the full [CONTRIBUTING][2] guidelines.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Contributors retain copyright to their work, and can request removal at any time.
|
Contributors retain copyright to their work, and can request removal at any
|
||||||
By uploading a doc here, you agree to publish your work under the default
|
time. By uploading a doc here, you agree to publish your work under the default
|
||||||
[Creative Commons Attribution-ShareAlike 3.0 Unported][3]
|
[Creative Commons Attribution-ShareAlike 3.0 Unported][3] licensing included on
|
||||||
licensing included on each doc page.
|
each doc page.
|
||||||
|
|
||||||
Anything not covered by the above -- basically, this README -- you can use
|
Anything not covered by the above -- basically, this README -- you can use as
|
||||||
as you wish, I guess.
|
you wish, I guess.
|
||||||
|
|
||||||
|
|
||||||
[1]: http://learnxinyminutes.com
|
[1]: http://learnxinyminutes.com
|
||||||
[2]: https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown
|
[2]: /CONTRIBUTING.markdown
|
||||||
[3]: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US
|
[3]: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US
|
||||||
|
122
asciidoc.html.markdown
Normal file
122
asciidoc.html.markdown
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
---
|
||||||
|
language: asciidoc
|
||||||
|
contributors:
|
||||||
|
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
|
||||||
|
filename: asciidoc.md
|
||||||
|
---
|
||||||
|
|
||||||
|
AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization.
|
||||||
|
|
||||||
|
Document Header
|
||||||
|
|
||||||
|
Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line.
|
||||||
|
|
||||||
|
Title Only
|
||||||
|
|
||||||
|
```
|
||||||
|
= Document Title
|
||||||
|
|
||||||
|
First sentence of document.
|
||||||
|
```
|
||||||
|
|
||||||
|
Title and Author
|
||||||
|
|
||||||
|
```
|
||||||
|
= Document Title
|
||||||
|
First Last <first.last@learnxinyminutes.com>
|
||||||
|
|
||||||
|
Start of this document.
|
||||||
|
```
|
||||||
|
|
||||||
|
Multiple Authors
|
||||||
|
|
||||||
|
```
|
||||||
|
= Document Title
|
||||||
|
John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
|
||||||
|
|
||||||
|
Start of a doc with multiple authors.
|
||||||
|
```
|
||||||
|
|
||||||
|
Revision Line (requires an author line)
|
||||||
|
|
||||||
|
```
|
||||||
|
= Doc Title V1
|
||||||
|
Potato Man <chip@crunchy.com>
|
||||||
|
v1.0, 2016-01-13
|
||||||
|
|
||||||
|
This article about chips is going to be fun.
|
||||||
|
```
|
||||||
|
|
||||||
|
Paragraphs
|
||||||
|
|
||||||
|
```
|
||||||
|
You don't need anything special for paragraphs.
|
||||||
|
|
||||||
|
Add a blank line between paragraphs to seperate them.
|
||||||
|
|
||||||
|
To create a line blank add a +
|
||||||
|
and you will recieve a line break!
|
||||||
|
```
|
||||||
|
|
||||||
|
Formatting Text
|
||||||
|
|
||||||
|
```
|
||||||
|
_underscore creates italics_
|
||||||
|
*asterisks for bold*
|
||||||
|
*_combine for extra fun_*
|
||||||
|
`use ticks to signify monospace`
|
||||||
|
`*bolded monospace*`
|
||||||
|
```
|
||||||
|
|
||||||
|
Section Titles
|
||||||
|
|
||||||
|
```
|
||||||
|
= Level 0 (may only be used in document's header)
|
||||||
|
|
||||||
|
== Level 1 <h2>
|
||||||
|
|
||||||
|
=== Level 2 <h3>
|
||||||
|
|
||||||
|
==== Level 3 <h4>
|
||||||
|
|
||||||
|
===== Level 4 <h5>
|
||||||
|
|
||||||
|
====== Level 5 <h6>
|
||||||
|
|
||||||
|
======= Level 6 <h7>
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Lists
|
||||||
|
|
||||||
|
To create a bulleted list use asterisks.
|
||||||
|
|
||||||
|
```
|
||||||
|
* foo
|
||||||
|
* bar
|
||||||
|
* baz
|
||||||
|
```
|
||||||
|
|
||||||
|
To create a numbered list use periods.
|
||||||
|
|
||||||
|
```
|
||||||
|
. item 1
|
||||||
|
. item 2
|
||||||
|
. item 3
|
||||||
|
```
|
||||||
|
|
||||||
|
You can nest lists by adding extra asterisks or periods up to five times.
|
||||||
|
|
||||||
|
```
|
||||||
|
* foo 1
|
||||||
|
** foo 2
|
||||||
|
*** foo 3
|
||||||
|
**** foo 4
|
||||||
|
***** foo 5
|
||||||
|
|
||||||
|
. foo 1
|
||||||
|
.. foo 2
|
||||||
|
... foo 3
|
||||||
|
.... foo 4
|
||||||
|
..... foo 5
|
||||||
|
```
|
@ -83,7 +83,7 @@ echo Hello, $Name!
|
|||||||
|
|
||||||
# We have the usual if structure:
|
# We have the usual if structure:
|
||||||
# use 'man test' for more info about conditionals
|
# use 'man test' for more info about conditionals
|
||||||
if [ $Name -ne $USER ]
|
if [ $Name != $USER ]
|
||||||
then
|
then
|
||||||
echo "Your name isn't your username"
|
echo "Your name isn't your username"
|
||||||
else
|
else
|
||||||
@ -91,12 +91,12 @@ else
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# NOTE: if $Name is empty, bash sees the above condition as:
|
# NOTE: if $Name is empty, bash sees the above condition as:
|
||||||
if [ -ne $USER ]
|
if [ != $USER ]
|
||||||
# which is invalid syntax
|
# which is invalid syntax
|
||||||
# so the "safe" way to use potentially empty variables in bash is:
|
# so the "safe" way to use potentially empty variables in bash is:
|
||||||
if [ "$Name" -ne $USER ] ...
|
if [ "$Name" != $USER ] ...
|
||||||
# which, when $Name is empty, is seen by bash as:
|
# which, when $Name is empty, is seen by bash as:
|
||||||
if [ "" -ne $USER ] ...
|
if [ "" != $USER ] ...
|
||||||
# which works as expected
|
# which works as expected
|
||||||
|
|
||||||
# There is also conditional execution
|
# There is also conditional execution
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
@ -149,7 +149,7 @@ namespace First {
|
|||||||
namespace Second {
|
namespace Second {
|
||||||
void foo()
|
void foo()
|
||||||
{
|
{
|
||||||
printf("This is Second::foo\n")
|
printf("This is Second::foo\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -330,7 +330,7 @@ ECarTypes GetPreferredCarType()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// As of C++11 there is an easy way to assign a type to the enum which can be
|
// As of C++11 there is an easy way to assign a type to the enum which can be
|
||||||
// useful in serialization of data and converting enums back-and-forth between
|
// useful in serialization of data and converting enums back-and-forth between
|
||||||
// the desired type and their respective constants
|
// the desired type and their respective constants
|
||||||
enum ECarTypes : uint8_t
|
enum ECarTypes : uint8_t
|
||||||
{
|
{
|
||||||
@ -352,7 +352,7 @@ void WritePreferredCarTypeToFile(ECarTypes InputCarType)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// On the other hand you may not want enums to be accidentally cast to an integer
|
// On the other hand you may not want enums to be accidentally cast to an integer
|
||||||
// type or to other enums so it is instead possible to create an enum class which
|
// type or to other enums so it is instead possible to create an enum class which
|
||||||
// won't be implicitly converted
|
// won't be implicitly converted
|
||||||
enum class ECarTypes : uint8_t
|
enum class ECarTypes : uint8_t
|
||||||
{
|
{
|
||||||
@ -468,7 +468,7 @@ int main() {
|
|||||||
// Inheritance:
|
// Inheritance:
|
||||||
|
|
||||||
// This class inherits everything public and protected from the Dog class
|
// This class inherits everything public and protected from the Dog class
|
||||||
// as well as private but may not directly access private members/methods
|
// as well as private but may not directly access private members/methods
|
||||||
// without a public or protected method for doing so
|
// without a public or protected method for doing so
|
||||||
class OwnedDog : public Dog {
|
class OwnedDog : public Dog {
|
||||||
|
|
||||||
@ -801,6 +801,94 @@ void doSomethingWithAFile(const std::string& filename)
|
|||||||
// all automatically destroy their contents when they fall out of scope.
|
// all automatically destroy their contents when they fall out of scope.
|
||||||
// - Mutexes using lock_guard and unique_lock
|
// - Mutexes using lock_guard and unique_lock
|
||||||
|
|
||||||
|
// containers with object keys of non-primitive values (custom classes) require
|
||||||
|
// compare function in the object itself or as a function pointer. Primitives
|
||||||
|
// have default comparators, but you can override it.
|
||||||
|
class Foo {
|
||||||
|
public:
|
||||||
|
int j;
|
||||||
|
Foo(int a) : j(a) {}
|
||||||
|
};
|
||||||
|
struct compareFunction {
|
||||||
|
bool operator()(const Foo& a, const Foo& b) const {
|
||||||
|
return a.j < b.j;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
//this isn't allowed (although it can vary depending on compiler)
|
||||||
|
//std::map<Foo, int> fooMap;
|
||||||
|
std::map<Foo, int, compareFunction> fooMap;
|
||||||
|
fooMap[Foo(1)] = 1;
|
||||||
|
fooMap.find(Foo(1)); //true
|
||||||
|
|
||||||
|
///////////////////////////////////////
|
||||||
|
// Lambda Expressions (C++11 and above)
|
||||||
|
///////////////////////////////////////
|
||||||
|
|
||||||
|
// lambdas are a convenient way of defining an anonymous function
|
||||||
|
// object right at the location where it is invoked or passed as
|
||||||
|
// an argument to a function.
|
||||||
|
|
||||||
|
// For example, consider sorting a vector of pairs using the second
|
||||||
|
// value of the pair
|
||||||
|
|
||||||
|
vector<pair<int, int> > tester;
|
||||||
|
tester.push_back(make_pair(3, 6));
|
||||||
|
tester.push_back(make_pair(1, 9));
|
||||||
|
tester.push_back(make_pair(5, 0));
|
||||||
|
|
||||||
|
// Pass a lambda expression as third argument to the sort function
|
||||||
|
// sort is from the <algorithm> header
|
||||||
|
|
||||||
|
sort(tester.begin(), tester.end(), [](const pair<int, int>& lhs, const pair<int, int>& rhs) {
|
||||||
|
return lhs.second < rhs.second;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Notice the syntax of the lambda expression,
|
||||||
|
// [] in the lambda is used to "capture" variables
|
||||||
|
// The "Capture List" defines what from the outside of the lambda should be available inside the function body and how.
|
||||||
|
// It can be either:
|
||||||
|
// 1. a value : [x]
|
||||||
|
// 2. a reference : [&x]
|
||||||
|
// 3. any variable currently in scope by reference [&]
|
||||||
|
// 4. same as 3, but by value [=]
|
||||||
|
// Example:
|
||||||
|
|
||||||
|
vector<int> dog_ids;
|
||||||
|
// number_of_dogs = 3;
|
||||||
|
for(int i = 0; i < 3; i++) {
|
||||||
|
dog_ids.push_back(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
int weight[3] = {30, 50, 10};
|
||||||
|
|
||||||
|
// Say you want to sort dog_ids according to the dogs' weights
|
||||||
|
// So dog_ids should in the end become: [2, 0, 1]
|
||||||
|
|
||||||
|
// Here's where lambda expressions come in handy
|
||||||
|
|
||||||
|
sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) {
|
||||||
|
return weight[lhs] < weight[rhs];
|
||||||
|
});
|
||||||
|
// Note we captured "weight" by reference in the above example.
|
||||||
|
// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
|
||||||
|
|
||||||
|
///////////////////////////////
|
||||||
|
// Range For (C++11 and above)
|
||||||
|
///////////////////////////////
|
||||||
|
|
||||||
|
// You can use a range for loop to iterate over a container
|
||||||
|
int arr[] = {1, 10, 3};
|
||||||
|
|
||||||
|
for(int elem: arr){
|
||||||
|
cout << elem << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// You can use "auto" and not worry about the type of the elements of the container
|
||||||
|
// For example:
|
||||||
|
|
||||||
|
for(auto elem: arr) {
|
||||||
|
// Do something with each element of arr
|
||||||
|
}
|
||||||
|
|
||||||
/////////////////////
|
/////////////////////
|
||||||
// Fun stuff
|
// Fun stuff
|
||||||
@ -852,20 +940,50 @@ Foo f1;
|
|||||||
f1 = f2;
|
f1 = f2;
|
||||||
|
|
||||||
|
|
||||||
// How to truly clear a container:
|
///////////////////////////////////////
|
||||||
class Foo { ... };
|
// Tuples (C++11 and above)
|
||||||
vector<Foo> v;
|
///////////////////////////////////////
|
||||||
for (int i = 0; i < 10; ++i)
|
|
||||||
v.push_back(Foo());
|
|
||||||
|
|
||||||
// Following line sets size of v to 0, but destructors don't get called
|
#include<tuple>
|
||||||
// and resources aren't released!
|
|
||||||
v.empty();
|
|
||||||
v.push_back(Foo()); // New value is copied into the first Foo we inserted
|
|
||||||
|
|
||||||
// Truly destroys all values in v. See section about temporary objects for
|
// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members ,
|
||||||
// explanation of why this works.
|
// its elements are accessed by their order in the tuple.
|
||||||
v.swap(vector<Foo>());
|
|
||||||
|
// We start with constructing a tuple.
|
||||||
|
// Packing values into tuple
|
||||||
|
auto first = make_tuple(10, 'A');
|
||||||
|
const int maxN = 1e9;
|
||||||
|
const int maxL = 15;
|
||||||
|
auto second = make_tuple(maxN, maxL);
|
||||||
|
|
||||||
|
// printing elements of 'first' tuple
|
||||||
|
cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A
|
||||||
|
|
||||||
|
// printing elements of 'second' tuple
|
||||||
|
cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15
|
||||||
|
|
||||||
|
// Unpacking tuple into variables
|
||||||
|
|
||||||
|
int first_int;
|
||||||
|
char first_char;
|
||||||
|
tie(first_int, first_char) = first;
|
||||||
|
cout << first_int << " " << first_char << "\n"; // prints : 10 A
|
||||||
|
|
||||||
|
// We can also create tuple like this.
|
||||||
|
|
||||||
|
tuple<int, char, double> third(11, 'A', 3.14141);
|
||||||
|
// tuple_size returns number of elements in a tuple (as a constexpr)
|
||||||
|
|
||||||
|
cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3
|
||||||
|
|
||||||
|
// tuple_cat concatenates the elements of all the tuples in the same order.
|
||||||
|
|
||||||
|
auto concatenated_tuple = tuple_cat(first, second, third);
|
||||||
|
// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141)
|
||||||
|
|
||||||
|
cout << get<0>(concatenated_tuple) << "\n"; // prints: 10
|
||||||
|
cout << get<3>(concatenated_tuple) << "\n"; // prints: 15
|
||||||
|
cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A'
|
||||||
|
|
||||||
```
|
```
|
||||||
Further Reading:
|
Further Reading:
|
||||||
|
@ -76,7 +76,7 @@ int main (int argc, char** argv)
|
|||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Types
|
// Types
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
|
||||||
// All variables MUST be declared at the top of the current block scope
|
// All variables MUST be declared at the top of the current block scope
|
||||||
// we declare them dynamically along the code for the sake of the tutorial
|
// we declare them dynamically along the code for the sake of the tutorial
|
||||||
|
|
||||||
@ -148,15 +148,10 @@ int main (int argc, char** argv)
|
|||||||
printf("Enter the array size: "); // ask the user for an array size
|
printf("Enter the array size: "); // ask the user for an array size
|
||||||
int size;
|
int size;
|
||||||
fscanf(stdin, "%d", &size);
|
fscanf(stdin, "%d", &size);
|
||||||
char buf[size];
|
int var_length_array[size]; // declare the VLA
|
||||||
fgets(buf, sizeof buf, stdin);
|
|
||||||
|
|
||||||
// strtoul parses a string to an unsigned integer
|
|
||||||
size_t size2 = strtoul(buf, NULL, 10);
|
|
||||||
int var_length_array[size2]; // declare the VLA
|
|
||||||
printf("sizeof array = %zu\n", sizeof var_length_array);
|
printf("sizeof array = %zu\n", sizeof var_length_array);
|
||||||
|
|
||||||
// A possible outcome of this program may be:
|
// Example:
|
||||||
// > Enter the array size: 10
|
// > Enter the array size: 10
|
||||||
// > sizeof array = 40
|
// > sizeof array = 40
|
||||||
|
|
||||||
@ -244,7 +239,7 @@ int main (int argc, char** argv)
|
|||||||
z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
|
z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
|
||||||
|
|
||||||
// Increment and decrement operators:
|
// Increment and decrement operators:
|
||||||
char *s = "iLoveC";
|
char *s = "ILoveC";
|
||||||
int j = 0;
|
int j = 0;
|
||||||
s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
|
s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
|
||||||
j = 0;
|
j = 0;
|
||||||
@ -318,9 +313,15 @@ int main (int argc, char** argv)
|
|||||||
case 1:
|
case 1:
|
||||||
printf("Huh, 'a' equals 1!\n");
|
printf("Huh, 'a' equals 1!\n");
|
||||||
break;
|
break;
|
||||||
|
// Be careful - without a "break", execution continues until the
|
||||||
|
// next "break" is reached.
|
||||||
|
case 3:
|
||||||
|
case 4:
|
||||||
|
printf("Look at that.. 'a' is either 3, or 4\n");
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
// if `some_integral_expression` didn't match any of the labels
|
// if `some_integral_expression` didn't match any of the labels
|
||||||
fputs("error!\n", stderr);
|
fputs("Error!\n", stderr);
|
||||||
exit(-1);
|
exit(-1);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -345,8 +346,8 @@ int main (int argc, char** argv)
|
|||||||
https://ideone.com/GuPhd6
|
https://ideone.com/GuPhd6
|
||||||
this will print out "Error occured at i = 52 & j = 99."
|
this will print out "Error occured at i = 52 & j = 99."
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Typecasting
|
// Typecasting
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
@ -445,7 +446,7 @@ int main (int argc, char** argv)
|
|||||||
for (xx = 0; xx < 20; xx++) {
|
for (xx = 0; xx < 20; xx++) {
|
||||||
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
|
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
|
||||||
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
|
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
|
||||||
|
|
||||||
// Note that there is no standard way to get the length of a
|
// Note that there is no standard way to get the length of a
|
||||||
// dynamically allocated array in C. Because of this, if your arrays are
|
// dynamically allocated array in C. Because of this, if your arrays are
|
||||||
// going to be passed around your program a lot, you need another variable
|
// going to be passed around your program a lot, you need another variable
|
||||||
@ -496,7 +497,7 @@ int add_two_ints(int x1, int x2)
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
Functions are call by value. When a function is called, the arguments passed to
|
Functions are call by value. When a function is called, the arguments passed to
|
||||||
≈the function are copies of the original arguments (except arrays). Anything you
|
the function are copies of the original arguments (except arrays). Anything you
|
||||||
do to the arguments in the function do not change the value of the original
|
do to the arguments in the function do not change the value of the original
|
||||||
argument where the function was called.
|
argument where the function was called.
|
||||||
|
|
||||||
@ -721,13 +722,13 @@ typedef void (*my_fnp_type)(char *);
|
|||||||
|
|
||||||
/******************************* Header Files **********************************
|
/******************************* Header Files **********************************
|
||||||
|
|
||||||
Header files are an important part of c as they allow for the connection of c
|
Header files are an important part of c as they allow for the connection of c
|
||||||
source files and can simplify code and definitions by seperating them into
|
source files and can simplify code and definitions by seperating them into
|
||||||
seperate files.
|
seperate files.
|
||||||
|
|
||||||
Header files are syntaxtically similar to c source files but reside in ".h"
|
Header files are syntactically similar to c source files but reside in ".h"
|
||||||
files. They can be included in your c source file by using the precompiler
|
files. They can be included in your c source file by using the precompiler
|
||||||
command #include "example.h", given that example.h exists in the same directory
|
command #include "example.h", given that example.h exists in the same directory
|
||||||
as the c file.
|
as the c file.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
@ -629,7 +629,7 @@ for (i, j) in zip( toThisArray.domain, -100..#5 ){
|
|||||||
}
|
}
|
||||||
writeln( toThisArray );
|
writeln( toThisArray );
|
||||||
|
|
||||||
// This is all very important in undestanding why the statement
|
// This is all very important in understanding why the statement
|
||||||
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
|
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
|
||||||
// exhibits a runtime error.
|
// exhibits a runtime error.
|
||||||
// Even though the domain of the array and the loop-expression are
|
// Even though the domain of the array and the loop-expression are
|
||||||
@ -914,7 +914,7 @@ proc main(){
|
|||||||
[ val in myBigArray ] val = 1 / val; // Parallel operation
|
[ val in myBigArray ] val = 1 / val; // Parallel operation
|
||||||
|
|
||||||
// Atomic variables, common to many languages, are ones whose operations
|
// Atomic variables, common to many languages, are ones whose operations
|
||||||
// occur uninterupted. Multiple threads can both modify atomic variables
|
// occur uninterrupted. Multiple threads can both modify atomic variables
|
||||||
// and can know that their values are safe.
|
// and can know that their values are safe.
|
||||||
// Chapel atomic variables can be of type bool, int, uint, and real.
|
// Chapel atomic variables can be of type bool, int, uint, and real.
|
||||||
var uranium: atomic int;
|
var uranium: atomic int;
|
||||||
|
@ -3,13 +3,17 @@ language: coldfusion
|
|||||||
filename: learncoldfusion.cfm
|
filename: learncoldfusion.cfm
|
||||||
contributors:
|
contributors:
|
||||||
- ["Wayne Boka", "http://wboka.github.io"]
|
- ["Wayne Boka", "http://wboka.github.io"]
|
||||||
|
- ["Kevin Morris", "https://twitter.com/kevinmorris"]
|
||||||
---
|
---
|
||||||
|
|
||||||
ColdFusion is a scripting language for web development.
|
ColdFusion is a scripting language for web development.
|
||||||
[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
|
[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
|
||||||
|
|
||||||
```html
|
### CFML
|
||||||
|
_**C**old**F**usion **M**arkup **L**anguage_
|
||||||
|
ColdFusion started as a tag-based language. Almost all functionality is available using tags.
|
||||||
|
|
||||||
|
```html
|
||||||
<em>HTML tags have been provided for output readability</em>
|
<em>HTML tags have been provided for output readability</em>
|
||||||
|
|
||||||
<!--- Comments start with "<!---" and end with "--->" --->
|
<!--- Comments start with "<!---" and end with "--->" --->
|
||||||
@ -229,40 +233,38 @@ ColdFusion is a scripting language for web development.
|
|||||||
|
|
||||||
<em>Code for reference (Functions must return something to support IE)</em>
|
<em>Code for reference (Functions must return something to support IE)</em>
|
||||||
|
|
||||||
<pre>
|
<cfcomponent>
|
||||||
<cfcomponent>
|
<cfset this.hello = "Hello" />
|
||||||
<cfset this.hello = "Hello" />
|
<cfset this.world = "world" />
|
||||||
<cfset this.world = "world" />
|
|
||||||
|
|
||||||
<cffunction name="sayHello">
|
<cffunction name="sayHello">
|
||||||
<cfreturn this.hello & ", " & this.world & "!" />
|
<cfreturn this.hello & ", " & this.world & "!" />
|
||||||
</cffunction>
|
</cffunction>
|
||||||
|
|
||||||
<cffunction name="setHello">
|
<cffunction name="setHello">
|
||||||
<cfargument name="newHello" type="string" required="true" />
|
<cfargument name="newHello" type="string" required="true" />
|
||||||
|
|
||||||
<cfset this.hello = arguments.newHello />
|
<cfset this.hello = arguments.newHello />
|
||||||
|
|
||||||
<cfreturn true />
|
<cfreturn true />
|
||||||
</cffunction>
|
</cffunction>
|
||||||
|
|
||||||
<cffunction name="setWorld">
|
<cffunction name="setWorld">
|
||||||
<cfargument name="newWorld" type="string" required="true" />
|
<cfargument name="newWorld" type="string" required="true" />
|
||||||
|
|
||||||
<cfset this.world = arguments.newWorld />
|
<cfset this.world = arguments.newWorld />
|
||||||
|
|
||||||
<cfreturn true />
|
<cfreturn true />
|
||||||
</cffunction>
|
</cffunction>
|
||||||
|
|
||||||
<cffunction name="getHello">
|
<cffunction name="getHello">
|
||||||
<cfreturn this.hello />
|
<cfreturn this.hello />
|
||||||
</cffunction>
|
</cffunction>
|
||||||
|
|
||||||
<cffunction name="getWorld">
|
<cffunction name="getWorld">
|
||||||
<cfreturn this.world />
|
<cfreturn this.world />
|
||||||
</cffunction>
|
</cffunction>
|
||||||
</cfcomponent>
|
</cfcomponent>
|
||||||
</pre>
|
|
||||||
|
|
||||||
<cfset this.hello = "Hello" />
|
<cfset this.hello = "Hello" />
|
||||||
<cfset this.world = "world" />
|
<cfset this.world = "world" />
|
||||||
@ -314,8 +316,13 @@ ColdFusion is a scripting language for web development.
|
|||||||
<cfoutput><p>#getWorld()#</p></cfoutput>
|
<cfoutput><p>#getWorld()#</p></cfoutput>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### CFScript
|
||||||
|
_**C**old**F**usion **S**cript_
|
||||||
|
In recent years, the ColdFusion language has added script syntax to mirror tag functionality. When using an up-to-date CF server, almost all functionality is available using scrypt syntax.
|
||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
|
||||||
The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
|
The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
|
||||||
|
|
||||||
1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html)
|
1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html)
|
||||||
|
2. [Open Source Documentation](http://cfdocs.org/)
|
||||||
|
@ -339,7 +339,7 @@ nil ; for false - and the empty list
|
|||||||
|
|
||||||
;; The () in the above is the list of arguments for the function
|
;; The () in the above is the list of arguments for the function
|
||||||
(defun hello (name)
|
(defun hello (name)
|
||||||
(format nil "Hello, ~a " name))
|
(format nil "Hello, ~a" name))
|
||||||
|
|
||||||
(hello "Steve") ; => "Hello, Steve"
|
(hello "Steve") ; => "Hello, Steve"
|
||||||
|
|
||||||
@ -430,7 +430,7 @@ nil ; for false - and the empty list
|
|||||||
(defun walker (n)
|
(defun walker (n)
|
||||||
(if (zerop n)
|
(if (zerop n)
|
||||||
:walked
|
:walked
|
||||||
(walker (1- n))))
|
(walker (- n 1))))
|
||||||
|
|
||||||
(walker 5) ; => :walked
|
(walker 5) ; => :walked
|
||||||
|
|
||||||
@ -614,9 +614,16 @@ nil ; for false - and the empty list
|
|||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
|
||||||
[Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/)
|
* [Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/)
|
||||||
|
* [A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf)
|
||||||
|
|
||||||
|
|
||||||
|
## Extra Info
|
||||||
|
|
||||||
|
* [CLiki](http://www.cliki.net/)
|
||||||
|
* [common-lisp.net](https://common-lisp.net/)
|
||||||
|
* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl)
|
||||||
|
|
||||||
## Credits.
|
## Credits.
|
||||||
|
|
||||||
Lots of thanks to the Scheme people for rolling up a great starting
|
Lots of thanks to the Scheme people for rolling up a great starting
|
||||||
|
260
cs-cz/markdown.html.markdown
Normal file
260
cs-cz/markdown.html.markdown
Normal file
@ -0,0 +1,260 @@
|
|||||||
|
---
|
||||||
|
language: markdown
|
||||||
|
lang: cs-cz
|
||||||
|
contributors:
|
||||||
|
- ["Dan Turkel", "http://danturkel.com/"]
|
||||||
|
translators:
|
||||||
|
- ["Michal Martinek", "https://github.com/MichalMartinek"]
|
||||||
|
filename: markdown.md
|
||||||
|
lang: cs-cz
|
||||||
|
---
|
||||||
|
|
||||||
|
Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná
|
||||||
|
a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha
|
||||||
|
dalších formátů)
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
<!-- Markdown je nadstavba nad HTML, takže jakýkoliv kód HTML je validní
|
||||||
|
Markdown, to znamená, že můžeme používat HTML elementy, třeba jako komentář, a
|
||||||
|
nebudou ovlivněny parserem Markdownu. Avšak, pokud vytvoříte HTML element v
|
||||||
|
Markdownu, tak nemůžete používat syntaxi Markdownu uvnitř tohoto elementu. -->
|
||||||
|
|
||||||
|
<!-- Markdown se také mírně liší v jednotlivých interpretacích parseru. Tento
|
||||||
|
návod vás bude upozorňovat, které vlastnosti jsou obecné a které specifické pro
|
||||||
|
konkrétní parser. -->
|
||||||
|
|
||||||
|
<!-- Nadpisy -->
|
||||||
|
<!-- Můžete vytvořit HTML elementy <h1> až <h6> jednoduše tak, že text předsadíte
|
||||||
|
počtem křížků (#), podle toho jaké úrovně to má být nadpis -->
|
||||||
|
# Toto je <h1>
|
||||||
|
## Toto je <h2>
|
||||||
|
### Toto je <h3>
|
||||||
|
#### Toto je <h4>
|
||||||
|
##### Toto je <h5>
|
||||||
|
###### Toto je <h6>
|
||||||
|
|
||||||
|
<!-- Markdown obsahuje taky dvě další cesty, jak udělat h1 a h2 -->
|
||||||
|
Toto je h1
|
||||||
|
==========
|
||||||
|
|
||||||
|
Toto je h2
|
||||||
|
----------
|
||||||
|
|
||||||
|
<!-- Jednoduché stylování textu -->
|
||||||
|
<!-- Pomocí markdownu můžete text jednoduše označit jako kurzívu či tučný -->
|
||||||
|
|
||||||
|
*Tento text je kurzívou;*
|
||||||
|
_Stejně jako tento._
|
||||||
|
|
||||||
|
**Tento text je tučně**
|
||||||
|
__Stejně jako tento.__
|
||||||
|
|
||||||
|
***Tento text je obojí***
|
||||||
|
**_Jako tento!_**
|
||||||
|
*__A tento!__*
|
||||||
|
|
||||||
|
<!-- Ve verzi Markdownu od Githubu, máme k dispozici taky prošktrnutí: -->
|
||||||
|
|
||||||
|
~~Tento text je prošktrnutý.~~
|
||||||
|
|
||||||
|
<!-- Odstavce jsou jedna nebo více řádek textu, oddělených jednou nebo více prázdnými řádky. -->
|
||||||
|
|
||||||
|
Toto je odstavec. Píši odstavec, není to zábava?
|
||||||
|
|
||||||
|
Teď jsem v odstavci 2.
|
||||||
|
Jsem pořád v odstavci 2!
|
||||||
|
|
||||||
|
|
||||||
|
Toto je odstavec 3.
|
||||||
|
|
||||||
|
<!-- Chtěli jste někdy vložit znak <br /> tag? Můžete napsat na konec odstavce
|
||||||
|
dvě nebo více mezer a potom začít nový odstavec. -->
|
||||||
|
|
||||||
|
Tento odstavec končí dvěma mezerami.
|
||||||
|
|
||||||
|
Nad tímto odstavcem je <br />!
|
||||||
|
|
||||||
|
<!-- Blokové citace se dělají jednoduše pomocí znaku >. -->
|
||||||
|
|
||||||
|
> Toto je bloková citace. Můžete dokonce
|
||||||
|
> manuálně rozdělit řádky, a před každý vložit >, nebo nechat vaše řádky jakkoliv dlouhé, ať se zarovnají sami.
|
||||||
|
> Nedělá to rozdíl, dokud začínáte vždy znakem >.
|
||||||
|
|
||||||
|
> Můžu použít více než jednu
|
||||||
|
>> odsazení?
|
||||||
|
> Jak je to úhledné, že?
|
||||||
|
|
||||||
|
<!-- Seznamy -->
|
||||||
|
<!-- Nečíslovaný seznam můžete jednoduše udělat pomocí hvězdiček, plusů, nebo
|
||||||
|
pomlček -->
|
||||||
|
|
||||||
|
* Položka
|
||||||
|
* Položka
|
||||||
|
* Jinná položka
|
||||||
|
|
||||||
|
nebo
|
||||||
|
|
||||||
|
+ Položka
|
||||||
|
+ Položka
|
||||||
|
+ Další položka
|
||||||
|
|
||||||
|
nebo
|
||||||
|
|
||||||
|
- Položka
|
||||||
|
- Položka
|
||||||
|
- Další položka
|
||||||
|
|
||||||
|
<!-- Číslovaný seznam se dělají pomocí čísla a . -->
|
||||||
|
|
||||||
|
1. Položka jedna
|
||||||
|
2. Položka dvě
|
||||||
|
3. Položka tři
|
||||||
|
|
||||||
|
<!-- Nemusíte dokonce psát čísla správně a markdown je zobrazi správně,
|
||||||
|
ale nemusí to být vždy dobrý nápad -->
|
||||||
|
|
||||||
|
1. Položka jedna
|
||||||
|
1. Položka dvě
|
||||||
|
1. Položka tři
|
||||||
|
<!-- (Toto zobrazí to samě, jako příklad nadtím.) -->
|
||||||
|
|
||||||
|
<!-- Můžete také tvořit podseznamy -->
|
||||||
|
|
||||||
|
1. Položka jedna
|
||||||
|
2. Položka dvě
|
||||||
|
3. Položka tři
|
||||||
|
* Podpoložka
|
||||||
|
* Podpoložka
|
||||||
|
4. Položka čtyři
|
||||||
|
|
||||||
|
<!-- Existují i zašktávací seznamy. Toto vytvoří HTML checkboxy. -->
|
||||||
|
|
||||||
|
Boxy níže bez 'x' jsou nezašktrnuté checkboxy.
|
||||||
|
- [ ] První úkol
|
||||||
|
- [ ] Druhý úkol
|
||||||
|
Tento box bude zašktrnutý
|
||||||
|
- [x] Tento úkol byl dokončen
|
||||||
|
|
||||||
|
<!-- Bloky ködu -->
|
||||||
|
<!-- Můžete označit kód bloku (který používá <code> element) odsazením pomocí 4
|
||||||
|
mezer, nebo tabu -->
|
||||||
|
|
||||||
|
Toto je kód
|
||||||
|
Stejně jako toto
|
||||||
|
|
||||||
|
<!-- Můžete dokonce přidat další 4 mezery nebo tab pro další odsazení -->
|
||||||
|
|
||||||
|
moje_pole.each do |i|
|
||||||
|
puts i
|
||||||
|
end
|
||||||
|
|
||||||
|
<!-- Kód na řádku může být označen pomocí zpětných apostrofů ` -->
|
||||||
|
|
||||||
|
Jan nevědel, jak se dělá `go_to()` funkce!
|
||||||
|
|
||||||
|
<!-- V Markdownu od Githubu , můžete použít speciální syntaxi pro kód -->
|
||||||
|
|
||||||
|
\`\`\`ruby <!-- vyjma zpětných lomítek, jenom ```ruby ! -->
|
||||||
|
def neco
|
||||||
|
puts "Ahoj světe!"
|
||||||
|
end
|
||||||
|
\`\`\` <!-- zde taky, žádné zpětná lomítka, pouze ``` -->
|
||||||
|
|
||||||
|
<!-- Text výše nepotřebuje odsazení a navíc Github použije zvýraznění označeného
|
||||||
|
jazyka. -->
|
||||||
|
|
||||||
|
<!-- Horizontální čára (<hr />) -->
|
||||||
|
<!-- Horizontální čára se jednoduše přidá pomocí 3 nebo více hvězdiček nebo pomlček
|
||||||
|
s nebo bez mezer. -->
|
||||||
|
|
||||||
|
***
|
||||||
|
---
|
||||||
|
- - -
|
||||||
|
****************
|
||||||
|
|
||||||
|
<!-- Odkazy -->
|
||||||
|
<!-- Jedna z nejlepších věcí na Markdownu je, jak jednoduše se dělají odkazy.
|
||||||
|
Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a je to. -->
|
||||||
|
|
||||||
|
[Klikni na mě!](http://test.com/)
|
||||||
|
|
||||||
|
<!-- Můžete také přidat jméno linku pomocí uvozovek -->
|
||||||
|
|
||||||
|
[Klikni na mě!](http://test.com/ "Odkaz na Test.com")
|
||||||
|
|
||||||
|
<!-- Relativní cesty fungují taky -->
|
||||||
|
|
||||||
|
[Jdi na hudbu](/hudba/).
|
||||||
|
|
||||||
|
<!-- Markdown taktéž podporuje reference odkazů. -->
|
||||||
|
|
||||||
|
[Klikni na tento odkaz][link1] pro více informací!
|
||||||
|
[Taky zkontrolujte tento odkaz][neco], když chcete.
|
||||||
|
|
||||||
|
[link1]: http://test.com/ "Cool!"
|
||||||
|
[neco]: http://neco.czz/ "Dobře!"
|
||||||
|
|
||||||
|
<!-- Titulek může být v apostrofech nebo závorkách, nebo vyjmutý úplně. Reference
|
||||||
|
může být kdekoliv ve vašem dokumentu a identifikátor může být jakýkoliv, dokud
|
||||||
|
je unikátní.-->
|
||||||
|
|
||||||
|
<!-- Také existuje "implicitní pojmenování", které použije text jako id -->
|
||||||
|
|
||||||
|
[Toto][] je odkaz..
|
||||||
|
|
||||||
|
[toto]: http://totojelink.cz/
|
||||||
|
|
||||||
|
<!-- Ale toto není zrovna běžné užívané. -->
|
||||||
|
|
||||||
|
<!-- Obrázky -->
|
||||||
|
<!-- Obrázky se dělají stejně jako odkazy, ale s vykřičníkem na začátku -->
|
||||||
|
|
||||||
|
![Toto je atribut alt pro obrázek](http://imgur.com/myimage.jpg "Nepovinný titulek")
|
||||||
|
|
||||||
|
<!-- Reference fungují, jak bychom čekali-->
|
||||||
|
|
||||||
|
![Toto je atribut alt][mujobrazek]
|
||||||
|
|
||||||
|
[mujobrazek]: relativni/cesta/obrazek.jpg "a toto by byl titulek"
|
||||||
|
|
||||||
|
<!-- Ostatní -->
|
||||||
|
<!-- Automatické odkazy -->
|
||||||
|
|
||||||
|
<http://stranka.cz/> je stejná jako
|
||||||
|
[http://stranka.cz/](http://stranka.cz/)
|
||||||
|
|
||||||
|
<!-- Automatické odkazy pro emaily-->
|
||||||
|
|
||||||
|
<jmeno@prijmeni.cz>
|
||||||
|
|
||||||
|
<!-- Escapování znaků -->
|
||||||
|
|
||||||
|
Chci napsat *tento text obklopený hvězdičkami*, ale nechci aby to bylo kurzívou, tak udělám: \*tento text obklopený hvězdičkami\*.
|
||||||
|
|
||||||
|
<!-- Klávesové zkratky -->
|
||||||
|
<!-- V Markdownu od Githubu, můžete použít tag <kbd> k reprezentování klaves na počítači -->
|
||||||
|
|
||||||
|
Váš počítač přestal pracovat? Zkuste
|
||||||
|
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||||
|
|
||||||
|
<!-- Tabulky -->
|
||||||
|
<!-- Tabulky jsou povolené pouze v Markdownu od Githubu a jsou trochu podivně,
|
||||||
|
ale když je opravdu chcete: -->
|
||||||
|
|
||||||
|
| Sloupec1 | Sloupec2 | Sloupec3 |
|
||||||
|
| :----------- | :------: | ------------: |
|
||||||
|
| Vlevo zarovn.| Na střed | Vpravo zarovn.|
|
||||||
|
| blah | blah | blah |
|
||||||
|
|
||||||
|
<!-- nebo, to jde i taky: -->
|
||||||
|
|
||||||
|
Sloupec 1 | Sloupec2 | Sloupec3
|
||||||
|
:-- | :-: | --:
|
||||||
|
Ohh toto je tak ošklivé | radši to | nedělejte
|
||||||
|
|
||||||
|
<!-- Konec -->
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Pro více informací, prozkoumejte oficiální článek o syntaxi od Johna Grubera
|
||||||
|
[zde](http://daringfireball.net/projects/markdown/syntax) a skvělý tahák od Adama Pritcharda [zde](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
@ -566,7 +566,7 @@ Clovek.odkaslej_si() # => "*ehm*"
|
|||||||
|
|
||||||
# Lze importovat moduly
|
# Lze importovat moduly
|
||||||
import math
|
import math
|
||||||
print(math.sqrt(16)) # => 4
|
print(math.sqrt(16.0)) # => 4
|
||||||
|
|
||||||
# Lze také importovat pouze vybrané funkce z modulu
|
# Lze také importovat pouze vybrané funkce z modulu
|
||||||
from math import ceil, floor
|
from math import ceil, floor
|
||||||
|
439
cs-cz/sass.html.markdown
Normal file
439
cs-cz/sass.html.markdown
Normal file
@ -0,0 +1,439 @@
|
|||||||
|
---
|
||||||
|
language: sass
|
||||||
|
filename: learnsass-cz.scss
|
||||||
|
contributors:
|
||||||
|
- ["Laura Kyle", "https://github.com/LauraNK"]
|
||||||
|
- ["Sean Corrales", "https://github.com/droidenator"]
|
||||||
|
translators:
|
||||||
|
- ["Michal Martinek", "https://github.com/MichalMartinek"]
|
||||||
|
lang: cs-cz
|
||||||
|
---
|
||||||
|
|
||||||
|
Sass je rozšíření jazyka CSS, který přidává nové vlastnosti jako proměnné, zanořování, mixiny a další.
|
||||||
|
Sass (a další preprocesory, jako [Less](http://lesscss.org/)) pomáhají vývojářům psát udržovatelný a neopakující (DRY) kód.
|
||||||
|
|
||||||
|
Sass nabízí dvě možnosti syntaxe. SCSS, které je stejná jako CSS, akorát obsahuje nové vlastnosti Sassu. Nebo Sass, který používá odsazení místo složených závorek a středníků.
|
||||||
|
Tento tutoriál bude používat syntaxi CSS.
|
||||||
|
|
||||||
|
|
||||||
|
Pokud jste již obeznámeni s CSS3, budete schopni používat Sass relativně rychle. Nezprostředkovává nějaké úplně nové stylové možnosti, spíše nátroje, jak psát Vás CSS kód více efektivně, udržitelně a jednoduše.
|
||||||
|
|
||||||
|
```scss
|
||||||
|
|
||||||
|
|
||||||
|
//Jednořádkové komentáře jsou ze Sassu při kompilaci vymazány
|
||||||
|
|
||||||
|
/*Víceřádkové komentáře jsou naopak zachovány */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Proměnné
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Můžete uložit CSS hodnotu (jako třeba barvu) do proměnné.
|
||||||
|
Použijte symbol '$' k jejímu vytvoření. */
|
||||||
|
|
||||||
|
$hlavni-barva: #A3A4FF;
|
||||||
|
$sekundarni-barva: #51527F;
|
||||||
|
$body-font: 'Roboto', sans-serif;
|
||||||
|
|
||||||
|
/* Můžete používat proměnné napříč vaším souborem.
|
||||||
|
Teď, když chcete změnit barvu, stačí ji změnit pouze jednou.*/
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: $hlavni-barva;
|
||||||
|
color: $sekundarni-barva;
|
||||||
|
font-family: $body-font;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toto se zkompiluje do: */
|
||||||
|
body {
|
||||||
|
background-color: #A3A4FF;
|
||||||
|
color: #51527F;
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* Toto je o hodně více praktické, než měnit každý výskyt barvy. */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Mixiny
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Pokud zjistíte, že píšete kód pro více než jeden element, můžete jej uložit do mixinu.
|
||||||
|
|
||||||
|
Použijte '@mixin' direktivu, plus jméno vašeho mixinu.*/
|
||||||
|
|
||||||
|
@mixin na-stred {
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Mixin vložíte pomocí '@include' a jména mixinu */
|
||||||
|
|
||||||
|
div {
|
||||||
|
@include na-stred;
|
||||||
|
background-color: $hlavni-barva;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*Což se zkompiluje do: */
|
||||||
|
div {
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background-color: #A3A4FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* Můžete využít mixiny i třeba pro takovéto ušetření práce: */
|
||||||
|
|
||||||
|
@mixin velikost($sirka, $vyska) {
|
||||||
|
width: $sirka;
|
||||||
|
height: $vyska;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*Stačí vložit argumenty: */
|
||||||
|
|
||||||
|
.obdelnik {
|
||||||
|
@include velikost(100px, 60px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ctverec {
|
||||||
|
@include velikost(40px, 40px);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toto se zkompiluje do: */
|
||||||
|
.obdelnik {
|
||||||
|
width: 100px;
|
||||||
|
height: 60px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ctverec {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Funkce
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Sass obsahuje funkce, které vám pomůžou splnit různé úkoly. */
|
||||||
|
|
||||||
|
/* Funkce se spouštějí pomocí jejich jména, které následuje seznam argumentů uzavřený v kulatých závorkách. */
|
||||||
|
body {
|
||||||
|
width: round(10.25px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer {
|
||||||
|
background-color: fade_out(#000000, 0.25)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Se zkompiluje do: */
|
||||||
|
|
||||||
|
body {
|
||||||
|
width: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer {
|
||||||
|
background-color: rgba(0, 0, 0, 0.75);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Můžete také definovat vlastní funkce. Funkce jsou velmi podobné mixinům.
|
||||||
|
Když se snažíte vybrat mezi funkcí a mixinem, mějte na paměti, že mixiny
|
||||||
|
jsou lepší pro generování CSS kódu, zatímco funkce jsou lepší pro logiku.
|
||||||
|
Příklady ze sekce Matematické operátory jsou skvělí kandidáti na
|
||||||
|
znovupoužitelné funkce. */
|
||||||
|
|
||||||
|
/* Tato funkce vrací poměr k velikosti rodiče v procentech.
|
||||||
|
@function vypocitat-pomer($velikost, $velikost-rodice) {
|
||||||
|
@return $velikost / $velikost-rodice * 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
$hlavni obsah: vypocitat-pomer(600px, 960px);
|
||||||
|
|
||||||
|
.hlavni-obsah {
|
||||||
|
width: $hlavni-obsah;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sloupec {
|
||||||
|
width: vypocitat-pomer(300px, 960px);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Zkompiluje do: */
|
||||||
|
|
||||||
|
.hlavni-obsah {
|
||||||
|
width: 62.5%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sloupec {
|
||||||
|
width: 31.25%;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Dědění
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Dědění je způsob jak používat vlastnosti pro jeden selektor ve druhém. */
|
||||||
|
|
||||||
|
.oznameni {
|
||||||
|
@include velikost(5em, 5em);
|
||||||
|
border: 5px solid $sekundarni-barva;
|
||||||
|
}
|
||||||
|
|
||||||
|
.oznameni-uspech {
|
||||||
|
@extend .oznameni;
|
||||||
|
border-color: #22df56;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Zkompiluje do: */
|
||||||
|
.oznameni, .oznameni-uspech {
|
||||||
|
width: 5em;
|
||||||
|
height: 5em;
|
||||||
|
border: 5px solid #51527F;
|
||||||
|
}
|
||||||
|
|
||||||
|
.oznameni-uspech {
|
||||||
|
border-color: #22df56;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* Dědění CSS výrazů je preferováno před vytvořením mixinu kvůli způsobu,
|
||||||
|
jakým způsobem Sass dává dohromady třídy, které sdílejí stejný kód.
|
||||||
|
Kdyby to bylo udělané pomocí mixinu, tak výška, šířka, rámeček by byl v
|
||||||
|
každém výrazu, který by volal mixin. I když tohle neovlivní vaše workflow,
|
||||||
|
přidá to kód navíc do souborů. */
|
||||||
|
|
||||||
|
|
||||||
|
/*Zanořování
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Sass vám umožňuje zanořovat selektory do selektorů */
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style-type: none;
|
||||||
|
margin-top: 2em;
|
||||||
|
|
||||||
|
li {
|
||||||
|
background-color: #FF0000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* '&' nahradí rodičovský element. */
|
||||||
|
/* Můžete také zanořovat pseudo třídy. */
|
||||||
|
/* Pamatujte, že moc velké zanoření do hloubky snižuje čitelnost.
|
||||||
|
Doporučuje se používat maximálně trojité zanoření.
|
||||||
|
Na příklad: */
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style-type: none;
|
||||||
|
margin-top: 2em;
|
||||||
|
|
||||||
|
li {
|
||||||
|
background-color: red;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background-color: blue;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Zkompiluje do: */
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style-type: none;
|
||||||
|
margin-top: 2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul li {
|
||||||
|
background-color: red;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul li:hover {
|
||||||
|
background-color: blue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul li a {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Částečné soubory a importy
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Sass umožňuje vytvářet částečné soubory. Tyto soubory pomahájí udržovat váš
|
||||||
|
kód modulární. Tyto soubory by měli začínat vždy '_', např. _reset.css.
|
||||||
|
Částečné soubory se nepřevádí do CSS. */
|
||||||
|
|
||||||
|
/* Toto je kód, který si uložíme do souboru _reset.css */
|
||||||
|
|
||||||
|
html,
|
||||||
|
body,
|
||||||
|
ul,
|
||||||
|
ol {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sass obsahuje @import, které může být použit pro import částečných souborů.
|
||||||
|
Toto se liší od klasického CSS @import, který dělá HTTP požadavek na stáhnutí
|
||||||
|
souboru. Sass vezme importovaný soubor a vloží ho do kompilovaného kódu. */
|
||||||
|
|
||||||
|
@import 'reset';
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-size: 16px;
|
||||||
|
font-family: Helvetica, Arial, Sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Zkompiluje do: */
|
||||||
|
|
||||||
|
html, body, ul, ol {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-size: 16px;
|
||||||
|
font-family: Helvetica, Arial, Sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Zástupné selektory
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Zástupné selektory jsou užitečné, když vytváříte CSS výraz, ze kterého
|
||||||
|
chcete později dědit. Když chcete vytvořit výraz, ze kterého je možné pouze
|
||||||
|
dědit pomocí @extend, vytvořte zástupný selektor s CSS výrazem. Ten začíná
|
||||||
|
symbolem '%' místo '.' nebo '#'. Tyto výrazy se neobjeví ve výsledném CSS */
|
||||||
|
|
||||||
|
%okno-obsahu {
|
||||||
|
font-size: 14px;
|
||||||
|
padding: 10px;
|
||||||
|
color: #000;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.okno-zpravy {
|
||||||
|
@extend %okno-obsahu;
|
||||||
|
background-color: #0000ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Zkompiluje do: */
|
||||||
|
|
||||||
|
.okno-zpravy {
|
||||||
|
font-size: 14px;
|
||||||
|
padding: 10px;
|
||||||
|
color: #000;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.okno-zpravy {
|
||||||
|
background-color: #0000ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Matematické operace
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Sass obsahuje následující operátory: +, -, *, /, and %. Tyto operátory
|
||||||
|
můžou být velmi užitečné pro počítání hodnot přímo ve vašem souboru Sass.
|
||||||
|
Níže je příklad, jak udělat jednoduchý dvousloupcový layout. */
|
||||||
|
|
||||||
|
$oblast-obsahu: 960px;
|
||||||
|
$hlavni-obsah: 600px;
|
||||||
|
$vedlejsi-sloupec: 300px;
|
||||||
|
|
||||||
|
$obsah-velikost: $hlavni-obsah / $oblast-obsahu * 100%;
|
||||||
|
$vedlejsi-sloupec-velikost: $vedlejsi-sloupec / $oblast-obsahu * 100%;
|
||||||
|
$zbytek-velikost: 100% - ($main-size + $vedlejsi-sloupec-size);
|
||||||
|
|
||||||
|
body {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hlavni-obsah {
|
||||||
|
width: $obsah-velikost;
|
||||||
|
}
|
||||||
|
|
||||||
|
.vedlejsi-sloupec {
|
||||||
|
width: $vedlejsi-sloupec-velikost;
|
||||||
|
}
|
||||||
|
|
||||||
|
.zbytek {
|
||||||
|
width: $zbytek-velikost;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Zkompiluje do: */
|
||||||
|
|
||||||
|
body {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hlavni-obsah {
|
||||||
|
width: 62.5%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.vedlejsi-sloupec {
|
||||||
|
width: 31.25%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gutter {
|
||||||
|
width: 6.25%;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## SASS nebo Sass?
|
||||||
|
Divili jste se někdy, jestli je Sass zkratka nebo ne? Pravděpodobně ne, ale řeknu vám to stejně. Jméno tohoto jazyka je slovo, "Sass", a ne zkratka.
|
||||||
|
Protože to lidé konstatně píší jako "SASS", nazval ho autor jazyka jako "Syntactically Awesome StyleSheets" (Syntaktický úžasně styly).
|
||||||
|
|
||||||
|
|
||||||
|
## Procvičování Sassu
|
||||||
|
Pokud si chcete hrát se Sassem ve vašem prohlížeči, navštivte [SassMeister](http://sassmeister.com/).
|
||||||
|
Můžete používát oba dva způsoby zápisu, stačí si vybrat v nastavení SCSS nebo SASS.
|
||||||
|
|
||||||
|
|
||||||
|
## Kompatibilita
|
||||||
|
|
||||||
|
Sass může být použit v jakémkoliv projektu, jakmile máte program, pomocí kterého ho zkompilujete do CSS. Pokud si chcete ověřit, že CSS, které Sass produkuje je kompatibilní s prohlížeči:
|
||||||
|
|
||||||
|
[QuirksMode CSS](http://www.quirksmode.org/css/) a [CanIUse](http://caniuse.com) jsou skvělé stránky pro kontrolu kompatibility.
|
||||||
|
|
||||||
|
|
||||||
|
## Kam dál?
|
||||||
|
* [Oficiální dokumentace](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
|
||||||
|
* [The Sass Way](http://thesassway.com/) obsahuje tutoriál a řadu skvělých článků
|
@ -45,8 +45,8 @@ using System.Data.Entity;
|
|||||||
// Using this code from another source file: using Learning.CSharp;
|
// Using this code from another source file: using Learning.CSharp;
|
||||||
namespace Learning.CSharp
|
namespace Learning.CSharp
|
||||||
{
|
{
|
||||||
// Each .cs file should at least contain a class with the same name as the file
|
// Each .cs file should at least contain a class with the same name as the file.
|
||||||
// you're allowed to do otherwise, but shouldn't for sanity.
|
// You're allowed to do otherwise, but shouldn't for sanity.
|
||||||
public class LearnCSharp
|
public class LearnCSharp
|
||||||
{
|
{
|
||||||
// BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
|
// BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
|
||||||
@ -630,7 +630,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
public static class Extensions
|
public static class Extensions
|
||||||
{
|
{
|
||||||
// EXTENSION FUNCTIONS
|
// EXTENSION METHODS
|
||||||
public static void Print(this object obj)
|
public static void Print(this object obj)
|
||||||
{
|
{
|
||||||
Console.WriteLine(obj.ToString());
|
Console.WriteLine(obj.ToString());
|
||||||
|
@ -6,20 +6,21 @@ contributors:
|
|||||||
- ["Geoffrey Liu", "https://github.com/g-liu"]
|
- ["Geoffrey Liu", "https://github.com/g-liu"]
|
||||||
- ["Connor Shea", "https://github.com/connorshea"]
|
- ["Connor Shea", "https://github.com/connorshea"]
|
||||||
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
|
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
|
||||||
|
- ["Tyler Mumford", "https://tylermumford.com"]
|
||||||
filename: learncss.css
|
filename: learncss.css
|
||||||
---
|
---
|
||||||
|
|
||||||
In the early days of the web there were no visual elements, just pure text. But with further development of web browsers, fully visual web pages also became common.
|
Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**.
|
||||||
|
|
||||||
CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page.
|
CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors.
|
||||||
|
|
||||||
CSS lets you target different elements on an HTML page and assign different visual properties to them.
|
This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3.
|
||||||
|
|
||||||
This guide has been written for CSS 2, though CSS 3 is fast becoming popular.
|
**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/).
|
||||||
|
|
||||||
**NOTE:** Because CSS produces visual results, in order to learn it, you need try everything in a CSS playground like [dabblet](http://dabblet.com/).
|
|
||||||
The main focus of this article is on the syntax and some general tips.
|
The main focus of this article is on the syntax and some general tips.
|
||||||
|
|
||||||
|
## Syntax
|
||||||
|
|
||||||
```css
|
```css
|
||||||
/* comments appear inside slash-asterisk, just like this line!
|
/* comments appear inside slash-asterisk, just like this line!
|
||||||
there are no "one-line comments"; this is the only comment style */
|
there are no "one-line comments"; this is the only comment style */
|
||||||
@ -28,7 +29,7 @@ The main focus of this article is on the syntax and some general tips.
|
|||||||
## SELECTORS
|
## SELECTORS
|
||||||
#################### */
|
#################### */
|
||||||
|
|
||||||
/* the selector is used to target an element on a page.
|
/* the selector is used to target an element on a page. */
|
||||||
selector { property: value; /* more properties...*/ }
|
selector { property: value; /* more properties...*/ }
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -69,7 +70,7 @@ div { }
|
|||||||
[otherAttr|='en'] { font-size:smaller; }
|
[otherAttr|='en'] { font-size:smaller; }
|
||||||
|
|
||||||
|
|
||||||
/* You can concatenate different selectors to create a narrower selector. Don't
|
/* You can combine different selectors to create a more focused selector. Don't
|
||||||
put spaces between them. */
|
put spaces between them. */
|
||||||
div.some-class[attr$='ue'] { }
|
div.some-class[attr$='ue'] { }
|
||||||
|
|
||||||
@ -92,7 +93,7 @@ div.some-parent.class-name { }
|
|||||||
.i-am-any-element-before ~ .this-element { }
|
.i-am-any-element-before ~ .this-element { }
|
||||||
|
|
||||||
/* There are some selectors called pseudo classes that can be used to select an
|
/* There are some selectors called pseudo classes that can be used to select an
|
||||||
element when it is in a particular state */
|
element only when it is in a particular state */
|
||||||
|
|
||||||
/* for example, when the cursor hovers over an element */
|
/* for example, when the cursor hovers over an element */
|
||||||
selector:hover { }
|
selector:hover { }
|
||||||
@ -103,7 +104,7 @@ selector:visited { }
|
|||||||
/* or hasn't been visited */
|
/* or hasn't been visited */
|
||||||
selected:link { }
|
selected:link { }
|
||||||
|
|
||||||
/* or an element in focus */
|
/* or an element is in focus */
|
||||||
selected:focus { }
|
selected:focus { }
|
||||||
|
|
||||||
/* any element that is the first child of its parent */
|
/* any element that is the first child of its parent */
|
||||||
@ -156,10 +157,10 @@ selector {
|
|||||||
color: tomato; /* a named color */
|
color: tomato; /* a named color */
|
||||||
color: rgb(255, 255, 255); /* as rgb values */
|
color: rgb(255, 255, 255); /* as rgb values */
|
||||||
color: rgb(10%, 20%, 50%); /* as rgb percentages */
|
color: rgb(10%, 20%, 50%); /* as rgb percentages */
|
||||||
color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */
|
color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */
|
||||||
color: transparent; /* equivalent to setting the alpha to 0 */
|
color: transparent; /* equivalent to setting the alpha to 0 */
|
||||||
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
|
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
|
||||||
color: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */
|
color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
|
||||||
|
|
||||||
/* Images as backgrounds of elements */
|
/* Images as backgrounds of elements */
|
||||||
background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
|
background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
|
||||||
@ -194,7 +195,7 @@ Save a CSS stylesheet with the extension `.css`.
|
|||||||
|
|
||||||
## Precedence or Cascade
|
## Precedence or Cascade
|
||||||
|
|
||||||
An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
|
An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
|
||||||
|
|
||||||
This process is called cascading, hence the name Cascading Style Sheets.
|
This process is called cascading, hence the name Cascading Style Sheets.
|
||||||
|
|
||||||
@ -238,10 +239,10 @@ Most of the features in CSS 2 (and many in CSS 3) are available across all brows
|
|||||||
|
|
||||||
## Resources
|
## Resources
|
||||||
|
|
||||||
* To run a quick compatibility check, [CanIUse](http://caniuse.com).
|
* [CanIUse](http://caniuse.com) (Detailed compatibility info)
|
||||||
* CSS Playground [Dabblet](http://dabblet.com/).
|
* [Dabblet](http://dabblet.com/) (CSS playground)
|
||||||
* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
|
* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference)
|
||||||
* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
|
* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference)
|
||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
|
||||||
|
@ -53,15 +53,15 @@ void main() {
|
|||||||
// For and while are nice, but in D-land we prefer 'foreach' loops.
|
// For and while are nice, but in D-land we prefer 'foreach' loops.
|
||||||
// The '..' creates a continuous range, including the first value
|
// The '..' creates a continuous range, including the first value
|
||||||
// but excluding the last.
|
// but excluding the last.
|
||||||
foreach(i; 1..1_000_000) {
|
foreach(n; 1..1_000_000) {
|
||||||
if(n % 2 == 0)
|
if(n % 2 == 0)
|
||||||
writeln(i);
|
writeln(n);
|
||||||
}
|
}
|
||||||
|
|
||||||
// There's also 'foreach_reverse' when you want to loop backwards.
|
// There's also 'foreach_reverse' when you want to loop backwards.
|
||||||
foreach_reverse(i; 1..int.max) {
|
foreach_reverse(n; 1..int.max) {
|
||||||
if(n % 2 == 1) {
|
if(n % 2 == 1) {
|
||||||
writeln(i);
|
writeln(n);
|
||||||
} else {
|
} else {
|
||||||
writeln("No!");
|
writeln("No!");
|
||||||
}
|
}
|
||||||
@ -70,7 +70,7 @@ void main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions
|
We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions
|
||||||
are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore,
|
are passed to functions by value (i.e. copied) and classes are passed by reference. Furthermore,
|
||||||
we can use templates to parameterize all of these on both types and values!
|
we can use templates to parameterize all of these on both types and values!
|
||||||
|
|
||||||
```c
|
```c
|
||||||
@ -199,8 +199,8 @@ our getter and setter methods, and keep the clean syntax of
|
|||||||
accessing members directly!
|
accessing members directly!
|
||||||
|
|
||||||
Other object-oriented goodies at our disposal
|
Other object-oriented goodies at our disposal
|
||||||
include `interface`s, `abstract class`es,
|
include interfaces, abstract classes,
|
||||||
and `override`ing methods. D does inheritance just like Java:
|
and overriding methods. D does inheritance just like Java:
|
||||||
Extend one class, implement as many interfaces as you please.
|
Extend one class, implement as many interfaces as you please.
|
||||||
|
|
||||||
We've seen D's OOP facilities, but let's switch gears. D offers
|
We've seen D's OOP facilities, but let's switch gears. D offers
|
||||||
@ -218,7 +218,7 @@ void main() {
|
|||||||
// from 1 to 100. Easy!
|
// from 1 to 100. Easy!
|
||||||
|
|
||||||
// Just pass lambda expressions as template parameters!
|
// Just pass lambda expressions as template parameters!
|
||||||
// You can pass any old function you like, but lambdas are convenient here.
|
// You can pass any function you like, but lambdas are convenient here.
|
||||||
auto num = iota(1, 101).filter!(x => x % 2 == 0)
|
auto num = iota(1, 101).filter!(x => x % 2 == 0)
|
||||||
.map!(y => y ^^ 2)
|
.map!(y => y ^^ 2)
|
||||||
.reduce!((a, b) => a + b);
|
.reduce!((a, b) => a + b);
|
||||||
@ -228,7 +228,7 @@ void main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notice how we got to build a nice Haskellian pipeline to compute num?
|
Notice how we got to build a nice Haskellian pipeline to compute num?
|
||||||
That's thanks to a D innovation know as Uniform Function Call Syntax.
|
That's thanks to a D innovation know as Uniform Function Call Syntax (UFCS).
|
||||||
With UFCS, we can choose whether to write a function call as a method
|
With UFCS, we can choose whether to write a function call as a method
|
||||||
or free function call! Walter wrote a nice article on this
|
or free function call! Walter wrote a nice article on this
|
||||||
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
|
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
|
||||||
@ -238,21 +238,23 @@ is of some type A on any expression of type A as a method.
|
|||||||
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
|
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
|
||||||
|
|
||||||
```c
|
```c
|
||||||
|
// Let's say we want to populate a large array with the square root of all
|
||||||
|
// consecutive integers starting from 1 (up until the size of the array), and we
|
||||||
|
// want to do this concurrently taking advantage of as many cores as we have
|
||||||
|
// available.
|
||||||
|
|
||||||
import std.stdio;
|
import std.stdio;
|
||||||
import std.parallelism : parallel;
|
import std.parallelism : parallel;
|
||||||
import std.math : sqrt;
|
import std.math : sqrt;
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
// We want take the square root every number in our array,
|
// Create your large array
|
||||||
// and take advantage of as many cores as we have available.
|
|
||||||
auto arr = new double[1_000_000];
|
auto arr = new double[1_000_000];
|
||||||
|
|
||||||
// Use an index, and an array element by referece,
|
// Use an index, access every array element by reference (because we're
|
||||||
// and just call parallel on the array!
|
// going to change each element) and just call parallel on the array!
|
||||||
foreach(i, ref elem; parallel(arr)) {
|
foreach(i, ref elem; parallel(arr)) {
|
||||||
ref = sqrt(i + 1.0);
|
elem = sqrt(i + 1.0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
@ -498,7 +498,7 @@ main() {
|
|||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
|
||||||
Dart has a comprehenshive web-site. It covers API reference, tutorials, articles and more, including a
|
Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
|
||||||
useful Try Dart online.
|
useful Try Dart online.
|
||||||
http://www.dartlang.org/
|
http://www.dartlang.org/
|
||||||
http://try.dartlang.org/
|
http://try.dartlang.org/
|
||||||
|
@ -4,17 +4,16 @@ filename: learngo-de.go
|
|||||||
contributors:
|
contributors:
|
||||||
- ["Joseph Adams", "https://github.com/jcla1"]
|
- ["Joseph Adams", "https://github.com/jcla1"]
|
||||||
- ["Dennis Keller", "https://github.com/denniskeller"]
|
- ["Dennis Keller", "https://github.com/denniskeller"]
|
||||||
|
- ["Jerome Meinke", "https://github.com/jmeinke"]
|
||||||
lang: de-de
|
lang: de-de
|
||||||
---
|
---
|
||||||
Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in
|
Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007
|
||||||
der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in
|
benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele
|
||||||
der realen Welt zu lösen.
|
Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und
|
||||||
|
benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente
|
||||||
Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung
|
für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen
|
||||||
und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu
|
Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten
|
||||||
verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern
|
erleichtert.
|
||||||
Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große
|
|
||||||
Programmierprojekte.
|
|
||||||
|
|
||||||
Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine
|
Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine
|
||||||
aktive Community.
|
aktive Community.
|
||||||
@ -24,8 +23,8 @@ aktive Community.
|
|||||||
/* Mehr-
|
/* Mehr-
|
||||||
zeiliger Kommentar */
|
zeiliger Kommentar */
|
||||||
|
|
||||||
// Eine jede Quelldatei beginnt mit einer Paket-Klausel.
|
// Wie bei Java gehört jede Quelldatei einem Paket an (Modularisierung).
|
||||||
// "main" ist ein besonderer Pkaetname, da er ein ausführbares Programm
|
// "main" ist ein besonderer Paketname, da er ein ausführbares Programm
|
||||||
// einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek
|
// einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek
|
||||||
// deklariert.
|
// deklariert.
|
||||||
package main
|
package main
|
||||||
@ -38,9 +37,9 @@ import (
|
|||||||
"strconv" // Zeichenkettenmanipulation
|
"strconv" // Zeichenkettenmanipulation
|
||||||
)
|
)
|
||||||
|
|
||||||
// Es folgt die Definition einer Funktions, in diesem Fall von "main". Auch hier
|
// Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier
|
||||||
// ist der Name wieder besonders. "main" markiert den Eintrittspunkt des
|
// ist der Name wieder besonders. "main" markiert den Eintrittspunkt des
|
||||||
// Programms. Vergessen Sie nicht die geschweiften Klammern!
|
// Programms.
|
||||||
func main() {
|
func main() {
|
||||||
// Println gibt eine Zeile zu stdout aus.
|
// Println gibt eine Zeile zu stdout aus.
|
||||||
// Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt.
|
// Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt.
|
||||||
@ -50,13 +49,13 @@ func main() {
|
|||||||
beyondHello()
|
beyondHello()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Funktionen können Parameter akzeptieren, diese werden in Klammern deklariert,
|
// Funktionen können Parameter akzeptieren. Diese werden in Klammern deklariert,
|
||||||
// die aber auch bei keinen Parametern erforderlich sind.
|
// die aber auch ohne Parameter erforderlich sind.
|
||||||
func beyondHello() {
|
func beyondHello() {
|
||||||
var x int // Deklaration einer Variable, muss vor Gebrauch geschehen.
|
var x int // Deklaration einer Variable, muss vor Gebrauch geschehen.
|
||||||
x = 3 // Zuweisung eines Werts.
|
x = 3 // Zuweisung eines Werts.
|
||||||
// Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu
|
// Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu
|
||||||
// folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen.
|
// folgern, die Variable zu deklarieren und ihr einen Wert zuzuweisen.
|
||||||
y := 4
|
y := 4
|
||||||
|
|
||||||
// Eine Funktion mit mehreren Rückgabewerten.
|
// Eine Funktion mit mehreren Rückgabewerten.
|
||||||
@ -99,7 +98,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
|
|||||||
// "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre
|
// "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre
|
||||||
// Vorzüge, aber slices werden viel häufiger verwendet
|
// Vorzüge, aber slices werden viel häufiger verwendet
|
||||||
s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse
|
s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse
|
||||||
s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Initialwert 0
|
s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Wert 0
|
||||||
var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung
|
var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung
|
||||||
bs := []byte("eine slice") // Umwandlungs-Syntax
|
bs := []byte("eine slice") // Umwandlungs-Syntax
|
||||||
|
|
||||||
@ -147,7 +146,7 @@ func learnFlowControl() {
|
|||||||
if false {
|
if false {
|
||||||
// nicht hier
|
// nicht hier
|
||||||
} else {
|
} else {
|
||||||
// sonder hier! spielt die Musik
|
// sondern hier! spielt die Musik
|
||||||
}
|
}
|
||||||
|
|
||||||
// Benutzen Sie ein "switch" Statement anstatt eine Anreihung von if-s
|
// Benutzen Sie ein "switch" Statement anstatt eine Anreihung von if-s
|
||||||
@ -166,7 +165,7 @@ func learnFlowControl() {
|
|||||||
// Ab hier gilt wieder: x == 1
|
// Ab hier gilt wieder: x == 1
|
||||||
|
|
||||||
// For ist die einzige Schleifenform in Go, sie hat aber mehrere Formen:
|
// For ist die einzige Schleifenform in Go, sie hat aber mehrere Formen:
|
||||||
for { // Endloschleife
|
for { // Endlosschleife
|
||||||
break // nur ein Spaß
|
break // nur ein Spaß
|
||||||
continue // wird nie ausgeführt
|
continue // wird nie ausgeführt
|
||||||
}
|
}
|
||||||
@ -201,7 +200,8 @@ type pair struct {
|
|||||||
x, y int
|
x, y int
|
||||||
}
|
}
|
||||||
|
|
||||||
// Definiere eine Methode von "pair". Dieser Typ erfüllt jetzt das Stringer interface.
|
// Definiere eine Methode von "pair".
|
||||||
|
// Dieser Typ erfüllt jetzt das Stringer interface.
|
||||||
func (p pair) String() string { // p ist der Empfänger
|
func (p pair) String() string { // p ist der Empfänger
|
||||||
// Sprintf ist eine weitere öffentliche Funktion von fmt.
|
// Sprintf ist eine weitere öffentliche Funktion von fmt.
|
||||||
// Der Syntax mit Punkt greift auf die Felder zu.
|
// Der Syntax mit Punkt greift auf die Felder zu.
|
||||||
@ -255,18 +255,19 @@ func learnConcurrency() {
|
|||||||
// Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für
|
// Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für
|
||||||
// maps, slices und Kanäle.
|
// maps, slices und Kanäle.
|
||||||
c := make(chan int)
|
c := make(chan int)
|
||||||
// Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently)
|
// Starte drei parallele "Goroutines".
|
||||||
// erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal.
|
// Die Zahlen werden parallel (concurrently) erhöht.
|
||||||
|
// Alle drei senden ihr Ergebnis in den gleichen Kanal.
|
||||||
go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine
|
go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine
|
||||||
go inc(10, c)
|
go inc(10, c)
|
||||||
go inc(-805, c)
|
go inc(-805, c)
|
||||||
// Auslesen und dann Ausgeben der drei berechneten Werte.
|
// Auslesen und dann Ausgeben der drei berechneten Werte.
|
||||||
// Man kann nicht im voraus feststellen in welcher Reihenfolge die Werte
|
// Man kann nicht im voraus feststellen in welcher Reihenfolge die Werte
|
||||||
// ankommen.
|
// ankommen.
|
||||||
fmt.Println(<-c, <-c, <-c) // mit dem Kannal rechts ist <- der Empfangs-Operator
|
fmt.Println(<-c, <-c, <-c) // mit dem Kanal rechts ist <- der Empfangs-Operator
|
||||||
|
|
||||||
cs := make(chan string) // ein weiterer Kannal, diesmal für strings
|
cs := make(chan string) // ein weiterer Kanal, diesmal für strings
|
||||||
cc := make(chan chan string) // ein Kannal für string Kannäle
|
cc := make(chan chan string) // ein Kanal für string Kanäle
|
||||||
|
|
||||||
// Start einer neuen Goroutine, nur um einen Wert zu senden
|
// Start einer neuen Goroutine, nur um einen Wert zu senden
|
||||||
go func() { c <- 84 }()
|
go func() { c <- 84 }()
|
||||||
@ -283,7 +284,7 @@ func learnConcurrency() {
|
|||||||
fmt.Println("wird nicht passieren.")
|
fmt.Println("wird nicht passieren.")
|
||||||
}
|
}
|
||||||
// Hier wird eine der beiden Goroutines fertig sein, die andere nicht.
|
// Hier wird eine der beiden Goroutines fertig sein, die andere nicht.
|
||||||
// Sie wird warten bis der Wert den sie sendet von dem Kannal gelesen wird.
|
// Sie wird warten bis der Wert den sie sendet von dem Kanal gelesen wird.
|
||||||
|
|
||||||
learnWebProgramming() // Go kann es und Sie hoffentlich auch bald.
|
learnWebProgramming() // Go kann es und Sie hoffentlich auch bald.
|
||||||
}
|
}
|
||||||
@ -301,19 +302,18 @@ func learnWebProgramming() {
|
|||||||
// Methode implementieren: ServeHTTP
|
// Methode implementieren: ServeHTTP
|
||||||
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
// Senden von Daten mit einer Methode des http.ResponseWriter
|
// Senden von Daten mit einer Methode des http.ResponseWriter
|
||||||
w.Write([]byte("Sie habe Go in Y Minuten gelernt!"))
|
w.Write([]byte("Sie haben Go in Y Minuten gelernt!"))
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Weitere Resourcen
|
## Weitere Resourcen
|
||||||
Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/).
|
Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/).
|
||||||
Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel
|
Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor
|
||||||
Dokumentation lesen.
|
allem aber Dokumentation zur Sprache und den Paketen.
|
||||||
|
|
||||||
Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr
|
Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr
|
||||||
kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
|
kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
|
||||||
ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/).
|
ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/)
|
||||||
Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil
|
einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil
|
||||||
verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen
|
verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen
|
||||||
in der [offiziellen Dokumentation von Go](http://golang.org/pkg/).
|
in der [offiziellen Dokumentation von Go](http://golang.org/pkg/).
|
||||||
|
|
||||||
|
@ -5,6 +5,7 @@ contributors:
|
|||||||
- ["Adit Bhargava", "http://adit.io"]
|
- ["Adit Bhargava", "http://adit.io"]
|
||||||
translators:
|
translators:
|
||||||
- ["Henrik Jürges", "https://github.com/santifa"]
|
- ["Henrik Jürges", "https://github.com/santifa"]
|
||||||
|
- ["Nikolai Weh", "http://weh.hamburg"]
|
||||||
filename: haskell-de.hs
|
filename: haskell-de.hs
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -58,12 +59,13 @@ not False -- True
|
|||||||
-- Strings und Zeichen
|
-- Strings und Zeichen
|
||||||
"Das ist ein String."
|
"Das ist ein String."
|
||||||
'a' -- Zeichen
|
'a' -- Zeichen
|
||||||
'Einfache Anfuehrungszeichen gehen nicht.' -- error!
|
'Einfache Anführungszeichen gehen nicht.' -- error!
|
||||||
|
|
||||||
-- Strings können konkateniert werden.
|
-- Strings können konkateniert werden.
|
||||||
"Hello " ++ "world!" -- "Hello world!"
|
"Hello " ++ "world!" -- "Hello world!"
|
||||||
|
|
||||||
-- Ein String ist eine Liste von Zeichen.
|
-- Ein String ist eine Liste von Zeichen.
|
||||||
|
['H', 'a', 'l', 'l', 'o', '!'] -- "Hallo!"
|
||||||
"Das ist eine String" !! 0 -- 'D'
|
"Das ist eine String" !! 0 -- 'D'
|
||||||
|
|
||||||
|
|
||||||
@ -76,11 +78,23 @@ not False -- True
|
|||||||
[1, 2, 3, 4, 5]
|
[1, 2, 3, 4, 5]
|
||||||
[1..5]
|
[1..5]
|
||||||
|
|
||||||
-- Haskell unterstuetzt unendliche Listen!
|
-- Die zweite Variante nennt sich die "range"-Syntax.
|
||||||
[1..] -- Die Liste aller natuerlichen Zahlen
|
-- Ranges sind recht flexibel:
|
||||||
|
['A'..'F'] -- "ABCDEF"
|
||||||
|
|
||||||
|
-- Es ist möglich eine Schrittweite anzugeben:
|
||||||
|
[0,2..10] -- [0,2,4,6,8,10]
|
||||||
|
[5..1] -- [], da Haskell standardmässig inkrementiert.
|
||||||
|
[5,4..1] -- [5,4,3,2,1]
|
||||||
|
|
||||||
|
-- Der "!!"-Operator extrahiert das Element an einem bestimmten Index:
|
||||||
|
[1..10] !! 3 -- 4
|
||||||
|
|
||||||
|
-- Haskell unterstützt unendliche Listen!
|
||||||
|
[1..] -- Die Liste aller natürlichen Zahlen
|
||||||
|
|
||||||
-- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation"
|
-- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation"
|
||||||
-- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird.
|
-- unterstützt. Haskell evaluiert erst etwas, wenn es benötigt wird.
|
||||||
-- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir:
|
-- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir:
|
||||||
|
|
||||||
[1..] !! 999 -- 1000
|
[1..] !! 999 -- 1000
|
||||||
@ -92,12 +106,9 @@ not False -- True
|
|||||||
-- Zwei Listen konkatenieren
|
-- Zwei Listen konkatenieren
|
||||||
[1..5] ++ [6..10]
|
[1..5] ++ [6..10]
|
||||||
|
|
||||||
-- Ein Element als Head hinzufuegen
|
-- Ein Element als Head hinzufügen
|
||||||
0:[1..5] -- [0, 1, 2, 3, 4, 5]
|
0:[1..5] -- [0, 1, 2, 3, 4, 5]
|
||||||
|
|
||||||
-- Gibt den 5. Index zurueck
|
|
||||||
[0..] !! 5 -- 5
|
|
||||||
|
|
||||||
-- Weitere Listenoperationen
|
-- Weitere Listenoperationen
|
||||||
head [1..5] -- 1
|
head [1..5] -- 1
|
||||||
tail [1..5] -- [2, 3, 4, 5]
|
tail [1..5] -- [2, 3, 4, 5]
|
||||||
@ -114,7 +125,8 @@ last [1..5] -- 5
|
|||||||
-- Ein Tupel:
|
-- Ein Tupel:
|
||||||
("haskell", 1)
|
("haskell", 1)
|
||||||
|
|
||||||
-- Auf Elemente eines Tupels zugreifen:
|
-- Ein Paar (Pair) ist ein Tupel mit 2 Elementen, auf die man wie folgt
|
||||||
|
-- zugreifen kann:
|
||||||
fst ("haskell", 1) -- "haskell"
|
fst ("haskell", 1) -- "haskell"
|
||||||
snd ("haskell", 1) -- 1
|
snd ("haskell", 1) -- 1
|
||||||
|
|
||||||
@ -140,9 +152,9 @@ add 1 2 -- 3
|
|||||||
(//) a b = a `div` b
|
(//) a b = a `div` b
|
||||||
35 // 4 -- 8
|
35 // 4 -- 8
|
||||||
|
|
||||||
-- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen.
|
-- Guards sind eine einfache Möglichkeit für Fallunterscheidungen.
|
||||||
fib x
|
fib x
|
||||||
| x < 2 = x
|
| x < 2 = 1
|
||||||
| otherwise = fib (x - 1) + fib (x - 2)
|
| otherwise = fib (x - 1) + fib (x - 2)
|
||||||
|
|
||||||
-- Pattern Matching funktioniert ähnlich.
|
-- Pattern Matching funktioniert ähnlich.
|
||||||
@ -174,7 +186,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15
|
|||||||
-- 4. Mehr Funktionen
|
-- 4. Mehr Funktionen
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
|
|
||||||
-- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt,
|
-- currying: Wenn man nicht alle Argumente an eine Funktion übergibt,
|
||||||
-- so wird sie eine neue Funktion gebildet ("curried").
|
-- so wird sie eine neue Funktion gebildet ("curried").
|
||||||
-- Es findet eine partielle Applikation statt und die neue Funktion
|
-- Es findet eine partielle Applikation statt und die neue Funktion
|
||||||
-- nimmt die fehlenden Argumente auf.
|
-- nimmt die fehlenden Argumente auf.
|
||||||
@ -190,23 +202,28 @@ foo 5 -- 15
|
|||||||
-- Funktionskomposition
|
-- Funktionskomposition
|
||||||
-- Die (.) Funktion verkettet Funktionen.
|
-- Die (.) Funktion verkettet Funktionen.
|
||||||
-- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
|
-- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
|
||||||
-- multipliziert dieses Ergebnis mit 5.
|
-- multipliziert dieses Ergebnis mit 4.
|
||||||
foo = (*5) . (+10)
|
foo = (*4) . (+10)
|
||||||
|
|
||||||
-- (5 + 10) * 5 = 75
|
-- (5 + 10) * 4 = 60
|
||||||
foo 5 -- 75
|
foo 5 -- 60
|
||||||
|
|
||||||
|
|
||||||
-- Haskell hat eine Funktion `$`. Diese ändert den Vorrang,
|
-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt.
|
||||||
-- so dass alles links von ihr zuerst berechnet wird und
|
-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist
|
||||||
-- und dann an die rechte Seite weitergegeben wird.
|
-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator
|
||||||
-- Mit `.` und `$` kann man sich viele Klammern ersparen.
|
-- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt,
|
||||||
|
-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die
|
||||||
|
-- Funktion auf der linken Seite verwendet wird.
|
||||||
|
-- Mit `.` und `$` kann man sich so viele Klammern ersparen.
|
||||||
|
|
||||||
-- Vorher
|
(even (fib 7)) -- false
|
||||||
(even (fib 7)) -- true
|
|
||||||
|
|
||||||
-- Danach
|
-- Äquivalent:
|
||||||
even . fib $ 7 -- true
|
even $ fib 7 -- false
|
||||||
|
|
||||||
|
-- Funktionskomposition:
|
||||||
|
even . fib $ 7 -- false
|
||||||
|
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
-- 5. Typensystem
|
-- 5. Typensystem
|
||||||
@ -221,31 +238,31 @@ even . fib $ 7 -- true
|
|||||||
True :: Bool
|
True :: Bool
|
||||||
|
|
||||||
-- Funktionen haben genauso Typen.
|
-- Funktionen haben genauso Typen.
|
||||||
-- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt:
|
-- `not` ist Funktion die ein Bool annimmt und ein Bool zurückgibt:
|
||||||
-- not :: Bool -> Bool
|
-- not :: Bool -> Bool
|
||||||
|
|
||||||
-- Eine Funktion die zwei Integer Argumente annimmt:
|
-- Eine Funktion die zwei Integer Argumente annimmt:
|
||||||
-- add :: Integer -> Integer -> Integer
|
-- add :: Integer -> Integer -> Integer
|
||||||
|
|
||||||
-- Es ist guter Stil zu jeder Funktionsdefinition eine
|
-- Es ist guter Stil zu jeder Funktionsdefinition eine
|
||||||
-- Typdefinition darueber zu schreiben:
|
-- Typdefinition darüber zu schreiben:
|
||||||
double :: Integer -> Integer
|
double :: Integer -> Integer
|
||||||
double x = x * 2
|
double x = x * 2
|
||||||
|
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
-- 6. If-Anweisung und Kontrollstrukturen
|
-- 6. If-Ausdrücke und Kontrollstrukturen
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
|
|
||||||
-- If-Anweisung:
|
-- If-Ausdruck:
|
||||||
haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
|
haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
|
||||||
|
|
||||||
-- If-Anweisungen können auch ueber mehrere Zeilen verteilt sein.
|
-- If-Ausdrücke können auch über mehrere Zeilen verteilt sein.
|
||||||
-- Das Einruecken ist dabei äußerst wichtig.
|
-- Die Einrückung ist dabei wichtig.
|
||||||
haskell = if 1 == 1
|
haskell = if 1 == 1
|
||||||
then "awesome"
|
then "awesome"
|
||||||
else "awful"
|
else "awful"
|
||||||
|
|
||||||
-- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen.
|
-- Case-Ausdruck: Am Beispiel vom Parsen von "commandline"-Argumenten.
|
||||||
case args of
|
case args of
|
||||||
"help" -> printHelp
|
"help" -> printHelp
|
||||||
"start" -> startProgram
|
"start" -> startProgram
|
||||||
@ -276,7 +293,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
|
|||||||
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
|
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
|
||||||
|
|
||||||
-- die Abarbeitung sieht so aus:
|
-- die Abarbeitung sieht so aus:
|
||||||
(2 * 3 + (2 * 2 + (2 * 1 + 4)))
|
(2 * 1 + (2 * 2 + (2 * 3 + 4)))
|
||||||
|
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
-- 7. Datentypen
|
-- 7. Datentypen
|
||||||
@ -300,7 +317,7 @@ data Maybe a = Nothing | Just a
|
|||||||
-- Diese sind alle vom Typ Maybe:
|
-- Diese sind alle vom Typ Maybe:
|
||||||
Just "hello" -- vom Typ `Maybe String`
|
Just "hello" -- vom Typ `Maybe String`
|
||||||
Just 1 -- vom Typ `Maybe Int`
|
Just 1 -- vom Typ `Maybe Int`
|
||||||
Nothing -- vom Typ `Maybe a` fuer jedes `a`
|
Nothing -- vom Typ `Maybe a` für jedes `a`
|
||||||
|
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
-- 8. Haskell IO
|
-- 8. Haskell IO
|
||||||
@ -309,8 +326,8 @@ Nothing -- vom Typ `Maybe a` fuer jedes `a`
|
|||||||
-- IO kann nicht völlig erklärt werden ohne Monaden zu erklären,
|
-- IO kann nicht völlig erklärt werden ohne Monaden zu erklären,
|
||||||
-- aber man kann die grundlegenden Dinge erklären.
|
-- aber man kann die grundlegenden Dinge erklären.
|
||||||
|
|
||||||
-- Wenn eine Haskell Programm ausgefuehrt wird, so wird `main` aufgerufen.
|
-- Wenn eine Haskell Programm ausgeführt wird, so wird `main` aufgerufen.
|
||||||
-- Diese muss etwas vom Typ `IO ()` zurueckgeben. Zum Beispiel:
|
-- Diese muss etwas vom Typ `IO ()` zurückgeben. Zum Beispiel:
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = putStrLn $ "Hello, sky! " ++ (say Blue)
|
main = putStrLn $ "Hello, sky! " ++ (say Blue)
|
||||||
@ -338,10 +355,10 @@ sayHello = do
|
|||||||
-- an die Variable "name" gebunden
|
-- an die Variable "name" gebunden
|
||||||
putStrLn $ "Hello, " ++ name
|
putStrLn $ "Hello, " ++ name
|
||||||
|
|
||||||
-- Uebung: Schreibe deine eigene Version von `interact`,
|
-- Übung: Schreibe deine eigene Version von `interact`,
|
||||||
-- die nur eine Zeile einliest.
|
-- die nur eine Zeile einliest.
|
||||||
|
|
||||||
-- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt.
|
-- `sayHello` wird niemals ausgeführt, nur `main` wird ausgeführt.
|
||||||
-- Um `sayHello` laufen zulassen kommentiere die Definition von `main`
|
-- Um `sayHello` laufen zulassen kommentiere die Definition von `main`
|
||||||
-- aus und ersetze sie mit:
|
-- aus und ersetze sie mit:
|
||||||
-- main = sayHello
|
-- main = sayHello
|
||||||
@ -359,7 +376,7 @@ action = do
|
|||||||
input1 <- getLine
|
input1 <- getLine
|
||||||
input2 <- getLine
|
input2 <- getLine
|
||||||
-- Der Typ von `do` ergibt sich aus der letzten Zeile.
|
-- Der Typ von `do` ergibt sich aus der letzten Zeile.
|
||||||
-- `return` ist eine Funktion und keine Schluesselwort
|
-- `return` ist eine Funktion und keine Schlüsselwort
|
||||||
return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
|
return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
|
||||||
|
|
||||||
-- Nun können wir `action` wie `getLine` benutzen:
|
-- Nun können wir `action` wie `getLine` benutzen:
|
||||||
@ -370,7 +387,7 @@ main'' = do
|
|||||||
putStrLn result
|
putStrLn result
|
||||||
putStrLn "This was all, folks!"
|
putStrLn "This was all, folks!"
|
||||||
|
|
||||||
-- Der Typ `IO` ist ein Beispiel fuer eine Monade.
|
-- Der Typ `IO` ist ein Beispiel für eine Monade.
|
||||||
-- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit
|
-- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit
|
||||||
-- eine rein funktional Sprache zu sein.
|
-- eine rein funktional Sprache zu sein.
|
||||||
-- Jede Funktion die mit der Außenwelt interagiert (z.B. IO)
|
-- Jede Funktion die mit der Außenwelt interagiert (z.B. IO)
|
||||||
@ -387,7 +404,7 @@ main'' = do
|
|||||||
|
|
||||||
-- Starte die REPL mit dem Befehl `ghci`
|
-- Starte die REPL mit dem Befehl `ghci`
|
||||||
-- Nun kann man Haskell Code eingeben.
|
-- Nun kann man Haskell Code eingeben.
|
||||||
-- Alle neuen Werte muessen mit `let` gebunden werden:
|
-- Alle neuen Werte müssen mit `let` gebunden werden:
|
||||||
|
|
||||||
let foo = 5
|
let foo = 5
|
||||||
|
|
||||||
@ -396,7 +413,7 @@ let foo = 5
|
|||||||
>:t foo
|
>:t foo
|
||||||
foo :: Integer
|
foo :: Integer
|
||||||
|
|
||||||
-- Auch jede `IO ()` Funktion kann ausgefuehrt werden.
|
-- Auch jede `IO ()` Funktion kann ausgeführt werden.
|
||||||
|
|
||||||
> sayHello
|
> sayHello
|
||||||
What is your name?
|
What is your name?
|
||||||
@ -420,6 +437,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
|
|||||||
Haskell ist sehr einfach zu installieren.
|
Haskell ist sehr einfach zu installieren.
|
||||||
Hohl es dir von [hier](http://www.haskell.org/platform/).
|
Hohl es dir von [hier](http://www.haskell.org/platform/).
|
||||||
|
|
||||||
Eine sehr viele langsamere Einfuehrung findest du unter:
|
Eine sehr viele langsamere Einführung findest du unter:
|
||||||
[Learn you a Haskell](http://learnyouahaskell.com/) oder
|
[Learn you a Haskell](http://learnyouahaskell.com/) oder
|
||||||
[Real World Haskell](http://book.realworldhaskell.org/).
|
[Real World Haskell](http://book.realworldhaskell.org/).
|
||||||
|
@ -6,19 +6,19 @@ contributors:
|
|||||||
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
|
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
|
||||||
translators:
|
translators:
|
||||||
- ["Moritz Kammerer", "https://github.com/phxql"]
|
- ["Moritz Kammerer", "https://github.com/phxql"]
|
||||||
|
- ["Jerome Meinke", "https://github.com/jmeinke"]
|
||||||
lang: de-de
|
lang: de-de
|
||||||
filename: latex-de.tex
|
filename: latex-de.tex
|
||||||
---
|
---
|
||||||
```
|
```
|
||||||
% Alle Kommentare starten fangen mit % an
|
% Alle Kommentare starten mit einem Prozentzeichen %
|
||||||
% Es gibt keine Kommentare über mehrere Zeilen
|
|
||||||
|
|
||||||
% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B.
|
% LaTeX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B.
|
||||||
% MS Word oder OpenOffice Writer
|
% MS Word oder OpenOffice Writer
|
||||||
|
|
||||||
% Jedes LateX-Kommando startet mit einem Backslash (\)
|
% Jedes LaTeX-Kommando startet mit einem Backslash (\)
|
||||||
|
|
||||||
% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen
|
% LaTeX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen
|
||||||
% Weitere Dokumententypen sind z.B. book, report, presentations, etc.
|
% Weitere Dokumententypen sind z.B. book, report, presentations, etc.
|
||||||
% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall
|
% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall
|
||||||
% wollen wir einen 12 Punkte-Font verwenden.
|
% wollen wir einen 12 Punkte-Font verwenden.
|
||||||
@ -26,7 +26,7 @@ filename: latex-de.tex
|
|||||||
|
|
||||||
% Als nächstes definieren wir die Pakete, die wir verwenden wollen.
|
% Als nächstes definieren wir die Pakete, die wir verwenden wollen.
|
||||||
% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest,
|
% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest,
|
||||||
% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern.
|
% musst du die Fähigkeiten von LaTeX durch Hinzufügen von Paketen erweitern.
|
||||||
% Wir verwenden die Pakete float und caption für Bilder.
|
% Wir verwenden die Pakete float und caption für Bilder.
|
||||||
\usepackage{caption}
|
\usepackage{caption}
|
||||||
\usepackage{float}
|
\usepackage{float}
|
||||||
@ -34,30 +34,41 @@ filename: latex-de.tex
|
|||||||
% Mit diesem Paket können leichter Umlaute getippt werden
|
% Mit diesem Paket können leichter Umlaute getippt werden
|
||||||
\usepackage[utf8]{inputenc}
|
\usepackage[utf8]{inputenc}
|
||||||
|
|
||||||
|
% Es gibt eigentlich keine Kommentare über mehrere Zeilen, solche kann man
|
||||||
|
% aber selbst durch die Angabe eigener Kommandos definieren.
|
||||||
|
% Dieses Kommando kann man später benutzen.
|
||||||
|
\newcommand{\comment}[1]{}
|
||||||
|
|
||||||
% Es können durchaus noch weitere Optione für das Dokument gesetzt werden!
|
% Es können durchaus noch weitere Optione für das Dokument gesetzt werden!
|
||||||
\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
|
\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
|
||||||
\date{\today}
|
\date{\today}
|
||||||
\title{Learn LaTeX in Y Minutes!}
|
\title{Learn \LaTeX\ in Y Minutes!}
|
||||||
|
|
||||||
% Nun kann's losgehen mit unserem Dokument.
|
% Nun kann's losgehen mit unserem Dokument.
|
||||||
% Alles vor dieser Zeile wird die Preamble genannt.
|
% Alles vor dieser Zeile wird die Preamble genannt.
|
||||||
\begin{document}
|
\begin{document}
|
||||||
|
|
||||||
|
\comment{
|
||||||
|
Dies ist unser selbst-definierter Befehl
|
||||||
|
für mehrzeilige Kommentare.
|
||||||
|
}
|
||||||
|
|
||||||
% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann
|
% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann
|
||||||
% LateX für uns eine Titelseite generieren
|
% LaTeX für uns eine Titelseite generieren
|
||||||
\maketitle
|
\maketitle
|
||||||
|
|
||||||
% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an.
|
% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigen Befehl an.
|
||||||
% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem
|
% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem
|
||||||
% Inhalt erscheinen.
|
% Inhalt erscheinen.
|
||||||
% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar.
|
% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar.
|
||||||
\begin{abstract}
|
\begin{abstract}
|
||||||
LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee!
|
\LaTeX -Documentation geschrieben in \LaTeX ! Wie ungewöhnlich und garantiert nicht meine Idee!
|
||||||
\end{abstract}
|
\end{abstract}
|
||||||
|
|
||||||
% Section Befehle sind intuitiv.
|
% Section Befehle sind intuitiv.
|
||||||
% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen.
|
% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen.
|
||||||
\section{Einleitung}
|
\section{Einleitung}
|
||||||
Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen!
|
Hi, mein Name ist Moritz und zusammen werden wir \LaTeX\ erforschen!
|
||||||
|
|
||||||
\section{Noch eine section}
|
\section{Noch eine section}
|
||||||
Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection.
|
Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection.
|
||||||
@ -71,16 +82,16 @@ So ist's schon viel besser.
|
|||||||
|
|
||||||
% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung.
|
% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung.
|
||||||
% Das funktioniert auch bei anderen Befehlen.
|
% Das funktioniert auch bei anderen Befehlen.
|
||||||
\section*{Das ist eine unnummerierte section}
|
\section*{Das ist eine unnummerierte section}
|
||||||
Es müssen nicht alle sections nummeriert sein!
|
Es müssen nicht alle Sections nummeriert sein!
|
||||||
|
|
||||||
\section{Ein paar Notizen}
|
\section{Ein paar Notizen}
|
||||||
LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht.
|
\LaTeX\ ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht.
|
||||||
Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge
|
Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge
|
||||||
\textbackslash\textbackslash in den Code ein.\\
|
\textbackslash\textbackslash in den Code ein.\\
|
||||||
|
|
||||||
\section{Listen}
|
\section{Listen}
|
||||||
Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen,
|
Listen sind eine der einfachsten Dinge in \LaTeX. Ich muss morgen einkaufen gehen,
|
||||||
also lass uns eine Einkaufsliste schreiben:
|
also lass uns eine Einkaufsliste schreiben:
|
||||||
\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung.
|
\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung.
|
||||||
% \item bringt enumerate dazu, eins weiterzuzählen.
|
% \item bringt enumerate dazu, eins weiterzuzählen.
|
||||||
@ -96,7 +107,7 @@ also lass uns eine Einkaufsliste schreiben:
|
|||||||
|
|
||||||
\section{Mathe}
|
\section{Mathe}
|
||||||
|
|
||||||
Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen
|
Einer der Haupteinsatzzwecke von \LaTeX\ ist das Schreiben von akademischen
|
||||||
Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder
|
Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder
|
||||||
anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle
|
anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle
|
||||||
Symbole zu unserem Paper hinzuzufügen! \\
|
Symbole zu unserem Paper hinzuzufügen! \\
|
||||||
@ -106,18 +117,18 @@ Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstabe
|
|||||||
um nur ein paar zu nennen.\\
|
um nur ein paar zu nennen.\\
|
||||||
|
|
||||||
Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen
|
Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen
|
||||||
Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\
|
Papern. So schreibt man in \LaTeX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\
|
||||||
|
|
||||||
% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben,
|
% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LaTeX schreiben,
|
||||||
% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings
|
% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings
|
||||||
% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und
|
% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und
|
||||||
% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden.
|
% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden.
|
||||||
|
|
||||||
Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$.
|
Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$.
|
||||||
Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt!
|
Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den \LaTeX nicht kennt!
|
||||||
|
|
||||||
Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten:
|
Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten:
|
||||||
Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$),
|
Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$),
|
||||||
Logarithmus und Exponenten ($\log$, $\exp$),
|
Logarithmus und Exponenten ($\log$, $\exp$),
|
||||||
Grenzwerte ($\lim$), etc. haben vordefinierte Befehle.
|
Grenzwerte ($\lim$), etc. haben vordefinierte Befehle.
|
||||||
Lass uns eine Gleichung schreiben: \\
|
Lass uns eine Gleichung schreiben: \\
|
||||||
@ -127,7 +138,7 @@ $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\
|
|||||||
Brüche (Zähler / Nenner) können so geschrieben werden:
|
Brüche (Zähler / Nenner) können so geschrieben werden:
|
||||||
|
|
||||||
% 10 / 7
|
% 10 / 7
|
||||||
$^{10}/_{7}$
|
$^{10}/_{7}$
|
||||||
|
|
||||||
% Komplexere Brüche können so geschrieben werden:
|
% Komplexere Brüche können so geschrieben werden:
|
||||||
% \frac{Zähler}{Nenner}
|
% \frac{Zähler}{Nenner}
|
||||||
@ -142,19 +153,19 @@ Wir können Gleichungen auch in einer equation Umgebung verwenden.
|
|||||||
\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen
|
\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen
|
||||||
|
|
||||||
Wir können nun unsere Gleichung referenzieren!
|
Wir können nun unsere Gleichung referenzieren!
|
||||||
Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in
|
Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in
|
||||||
Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden:
|
Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden:
|
||||||
Grafiken, Gleichungen, Sections, etc.
|
Grafiken, Gleichungen, Sections, etc.
|
||||||
|
|
||||||
Summen und Integrale können mit den sum und int Befehlen dargestellt werden:
|
Summen und Integrale können mit den sum und int Befehlen dargestellt werden:
|
||||||
|
|
||||||
% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen
|
% Manche LaTeX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen
|
||||||
\begin{equation}
|
\begin{equation}
|
||||||
\sum_{i=0}^{5} f_{i}
|
\sum_{i=0}^{5} f_{i}
|
||||||
\end{equation}
|
\end{equation}
|
||||||
\begin{equation}
|
\begin{equation}
|
||||||
\int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
|
\int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
|
||||||
\end{equation}
|
\end{equation}
|
||||||
|
|
||||||
\section{Grafiken}
|
\section{Grafiken}
|
||||||
|
|
||||||
@ -164,7 +175,7 @@ Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt.
|
|||||||
\begin{figure}[H] % H ist die Platzierungsoption
|
\begin{figure}[H] % H ist die Platzierungsoption
|
||||||
\centering % Zentriert die Grafik auf der Seite
|
\centering % Zentriert die Grafik auf der Seite
|
||||||
% Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt.
|
% Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt.
|
||||||
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
|
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
|
||||||
% Auskommentiert, damit es nicht im Dokument auftaucht.
|
% Auskommentiert, damit es nicht im Dokument auftaucht.
|
||||||
\caption{Dreieck mit den Seiten $a$, $b$, $c$}
|
\caption{Dreieck mit den Seiten $a$, $b$, $c$}
|
||||||
\label{fig:right-triangle}
|
\label{fig:right-triangle}
|
||||||
@ -177,7 +188,7 @@ Wir können Tabellen genauso wie Grafiken einfügen.
|
|||||||
\caption{Überschrift der Tabelle.}
|
\caption{Überschrift der Tabelle.}
|
||||||
% Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll.
|
% Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll.
|
||||||
% Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal.
|
% Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal.
|
||||||
\begin{tabular}{c|cc}
|
\begin{tabular}{c|cc}
|
||||||
Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt
|
Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt
|
||||||
\hline % Eine horizontale Linie
|
\hline % Eine horizontale Linie
|
||||||
1 & Biggus & Dickus \\
|
1 & Biggus & Dickus \\
|
||||||
@ -187,36 +198,36 @@ Wir können Tabellen genauso wie Grafiken einfügen.
|
|||||||
|
|
||||||
% \section{Links} % Kommen bald!
|
% \section{Links} % Kommen bald!
|
||||||
|
|
||||||
\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)}
|
\section{Verhindern, dass \LaTeX\ etwas kompiliert (z.B. Quelltext)}
|
||||||
Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll
|
Angenommen, wir wollen Quelltext in unserem \LaTeX-Dokument. \LaTeX\ soll
|
||||||
in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren,
|
in diesem Fall nicht den Quelltext als \LaTeX-Kommandos interpretieren,
|
||||||
sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden
|
sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden
|
||||||
wir eine verbatim Umgebung.
|
wir eine verbatim Umgebung.
|
||||||
|
|
||||||
% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.)
|
% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.)
|
||||||
% aber verbatim ist das simpelste.
|
% aber verbatim ist das simpelste.
|
||||||
\begin{verbatim}
|
\begin{verbatim}
|
||||||
print("Hello World!")
|
print("Hello World!")
|
||||||
a%b; % Schau dir das an! Wir können % im verbatim verwenden!
|
a%b; % Schau dir das an! Wir können % im verbatim verwenden!
|
||||||
random = 4; #decided by fair random dice roll
|
random = 4; #decided by fair random dice roll
|
||||||
\end{verbatim}
|
\end{verbatim}
|
||||||
|
|
||||||
\section{Kompilieren}
|
\section{Kompilieren}
|
||||||
|
|
||||||
Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF
|
Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF
|
||||||
verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\
|
verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\
|
||||||
|
|
||||||
Dafür musst du folgende Schritte durchführen:
|
Dafür musst du folgende Schritte durchführen:
|
||||||
\begin{enumerate}
|
\begin{enumerate}
|
||||||
\item Schreibe das Dokument. (den LateX-Quelltext).
|
\item Schreibe das Dokument. (den \LaTeX -Quelltext).
|
||||||
\item Kompiliere den Quelltext in ein PDF.
|
\item Kompiliere den Quelltext in ein PDF.
|
||||||
Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\
|
Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\
|
||||||
\begin{verbatim}
|
\begin{verbatim}
|
||||||
$pdflatex learn-latex.tex learn-latex.pdf
|
$pdflatex learn-latex.tex learn-latex.pdf
|
||||||
\end{verbatim}
|
\end{verbatim}
|
||||||
\end{enumerate}
|
\end{enumerate}
|
||||||
|
|
||||||
Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt
|
Manche \LaTeX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt
|
||||||
2 wird unsichtbar im Hintergrund ausgeführt.
|
2 wird unsichtbar im Hintergrund ausgeführt.
|
||||||
|
|
||||||
Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet
|
Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -30,7 +30,7 @@ null_Wert: null
|
|||||||
Schlüssel mit Leerzeichen: value
|
Schlüssel mit Leerzeichen: value
|
||||||
# Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber:
|
# Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber:
|
||||||
jedoch: "Ein String in Anführungzeichen"
|
jedoch: "Ein String in Anführungzeichen"
|
||||||
"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schluessel haben willst."
|
"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schlüssel haben willst."
|
||||||
|
|
||||||
# Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text)
|
# Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text)
|
||||||
# oder ein 'folded block' (> gefolgt vom text).
|
# oder ein 'folded block' (> gefolgt vom text).
|
||||||
@ -64,7 +64,7 @@ eine_verschachtelte_map:
|
|||||||
hallo: hallo
|
hallo: hallo
|
||||||
|
|
||||||
# Schlüssel müssen nicht immer String sein.
|
# Schlüssel müssen nicht immer String sein.
|
||||||
0.25: ein Float-Wert als Schluessel
|
0.25: ein Float-Wert als Schlüssel
|
||||||
|
|
||||||
# Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels
|
# Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels
|
||||||
? |
|
? |
|
||||||
|
108
edn.html.markdown
Normal file
108
edn.html.markdown
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
---
|
||||||
|
language: edn
|
||||||
|
filename: learnedn.edn
|
||||||
|
contributors:
|
||||||
|
- ["Jason Yeo", "https://github.com/jsyeo"]
|
||||||
|
---
|
||||||
|
|
||||||
|
Extensible Data Notation (EDN) is a format for serializing data.
|
||||||
|
|
||||||
|
The notation is used internally by Clojure to represent programs. It is also
|
||||||
|
used as a data transfer format like JSON. Though it is more commonly used in
|
||||||
|
Clojure, there are implementations of EDN for many other languages.
|
||||||
|
|
||||||
|
The main benefit of EDN over JSON and YAML is that it is extensible. We
|
||||||
|
will see how it is extended later on.
|
||||||
|
|
||||||
|
```clojure
|
||||||
|
; Comments start with a semicolon.
|
||||||
|
; Anything after the semicolon is ignored.
|
||||||
|
|
||||||
|
;;;;;;;;;;;;;;;;;;;
|
||||||
|
;;; Basic Types ;;;
|
||||||
|
;;;;;;;;;;;;;;;;;;;
|
||||||
|
|
||||||
|
nil ; also known in other languages as null
|
||||||
|
|
||||||
|
; Booleans
|
||||||
|
true
|
||||||
|
false
|
||||||
|
|
||||||
|
; Strings are enclosed in double quotes
|
||||||
|
"hungarian breakfast"
|
||||||
|
"farmer's cheesy omelette"
|
||||||
|
|
||||||
|
; Characters are preceeded by backslashes
|
||||||
|
\g \r \a \c \e
|
||||||
|
|
||||||
|
; Keywords start with a colon. They behave like enums. Kind of
|
||||||
|
; like symbols in Ruby.
|
||||||
|
:eggs
|
||||||
|
:cheese
|
||||||
|
:olives
|
||||||
|
|
||||||
|
; Symbols are used to represent identifiers. They start with #.
|
||||||
|
; You can namespace symbols by using /. Whatever preceeds / is
|
||||||
|
; the namespace of the name.
|
||||||
|
#spoon
|
||||||
|
#kitchen/spoon ; not the same as #spoon
|
||||||
|
#kitchen/fork
|
||||||
|
#github/fork ; you can't eat with this
|
||||||
|
|
||||||
|
; Integers and floats
|
||||||
|
42
|
||||||
|
3.14159
|
||||||
|
|
||||||
|
; Lists are sequences of values
|
||||||
|
(:bun :beef-patty 9 "yum!")
|
||||||
|
|
||||||
|
; Vectors allow random access
|
||||||
|
[:gelato 1 2 -2]
|
||||||
|
|
||||||
|
; Maps are associative data structures that associate the key with its value
|
||||||
|
{:eggs 2
|
||||||
|
:lemon-juice 3.5
|
||||||
|
:butter 1}
|
||||||
|
|
||||||
|
; You're not restricted to using keywords as keys
|
||||||
|
{[1 2 3 4] "tell the people what she wore",
|
||||||
|
[5 6 7 8] "the more you see the more you hate"}
|
||||||
|
|
||||||
|
; You may use commas for readability. They are treated as whitespace.
|
||||||
|
|
||||||
|
; Sets are collections that contain unique elements.
|
||||||
|
#{:a :b 88 "huat"}
|
||||||
|
|
||||||
|
;;;;;;;;;;;;;;;;;;;;;;;
|
||||||
|
;;; Tagged Elements ;;;
|
||||||
|
;;;;;;;;;;;;;;;;;;;;;;;
|
||||||
|
|
||||||
|
; EDN can be extended by tagging elements with # symbols.
|
||||||
|
|
||||||
|
#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
|
||||||
|
|
||||||
|
; Let me explain this with a clojure example. Suppose I want to transform that
|
||||||
|
; piece of EDN into a MenuItem record.
|
||||||
|
|
||||||
|
(defrecord MenuItem [name rating])
|
||||||
|
|
||||||
|
; To transform EDN to clojure values, I will need to use the built in EDN
|
||||||
|
; reader, edn/read-string
|
||||||
|
|
||||||
|
(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
|
||||||
|
; -> {:eggs 2 :butter 1 :flour 5}
|
||||||
|
|
||||||
|
; To transform tagged elements, define the reader function and pass a map
|
||||||
|
; that maps tags to reader functions to edn/read-string like so
|
||||||
|
|
||||||
|
(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}}
|
||||||
|
"#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
|
||||||
|
; -> #user.MenuItem{:name "eggs-benedict", :rating 10}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
# References
|
||||||
|
|
||||||
|
- [EDN spec](https://github.com/edn-format/edn)
|
||||||
|
- [Implementations](https://github.com/edn-format/edn/wiki/Implementations)
|
||||||
|
- [Tagged Elements](http://www.compoundtheory.com/clojure-edn-walkthrough/)
|
@ -2,6 +2,7 @@
|
|||||||
language: elisp
|
language: elisp
|
||||||
contributors:
|
contributors:
|
||||||
- ["Bastien Guerry", "http://bzg.fr"]
|
- ["Bastien Guerry", "http://bzg.fr"]
|
||||||
|
- ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
|
||||||
filename: learn-emacs-lisp.el
|
filename: learn-emacs-lisp.el
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -26,7 +27,7 @@ filename: learn-emacs-lisp.el
|
|||||||
;;
|
;;
|
||||||
;; Going through this tutorial won't damage your computer unless
|
;; Going through this tutorial won't damage your computer unless
|
||||||
;; you get so angry that you throw it on the floor. In that case,
|
;; you get so angry that you throw it on the floor. In that case,
|
||||||
;; I hereby decline any responsability. Have fun!
|
;; I hereby decline any responsibility. Have fun!
|
||||||
|
|
||||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||||
;;
|
;;
|
||||||
|
@ -343,6 +343,7 @@ rescue
|
|||||||
RuntimeError -> "rescued a runtime error"
|
RuntimeError -> "rescued a runtime error"
|
||||||
_error -> "this will rescue any error"
|
_error -> "this will rescue any error"
|
||||||
end
|
end
|
||||||
|
#=> "rescued a runtime error"
|
||||||
|
|
||||||
# All exceptions have a message
|
# All exceptions have a message
|
||||||
try do
|
try do
|
||||||
@ -351,6 +352,7 @@ rescue
|
|||||||
x in [RuntimeError] ->
|
x in [RuntimeError] ->
|
||||||
x.message
|
x.message
|
||||||
end
|
end
|
||||||
|
#=> "some error"
|
||||||
|
|
||||||
## ---------------------------
|
## ---------------------------
|
||||||
## -- Concurrency
|
## -- Concurrency
|
||||||
|
367
elm.html.markdown
Normal file
367
elm.html.markdown
Normal file
@ -0,0 +1,367 @@
|
|||||||
|
---
|
||||||
|
language: Elm
|
||||||
|
contributors:
|
||||||
|
- ["Max Goldstein", "http://maxgoldste.in/"]
|
||||||
|
---
|
||||||
|
|
||||||
|
Elm is a functional reactive programming language that compiles to (client-side)
|
||||||
|
JavaScript. Elm is statically typed, meaning that the compiler catches most
|
||||||
|
errors immediately and provides a clear and understandable error message. Elm is
|
||||||
|
great for designing user interfaces and games for the web.
|
||||||
|
|
||||||
|
|
||||||
|
```haskell
|
||||||
|
-- Single line comments start with two dashes.
|
||||||
|
{- Multiline comments can be enclosed in a block like this.
|
||||||
|
{- They can be nested. -}
|
||||||
|
-}
|
||||||
|
|
||||||
|
{-- The Basics --}
|
||||||
|
|
||||||
|
-- Arithmetic
|
||||||
|
1 + 1 -- 2
|
||||||
|
8 - 1 -- 7
|
||||||
|
10 * 2 -- 20
|
||||||
|
|
||||||
|
-- Every number literal without a decimal point can be either an Int or a Float.
|
||||||
|
33 / 2 -- 16.5 with floating point division
|
||||||
|
33 // 2 -- 16 with integer division
|
||||||
|
|
||||||
|
-- Exponents
|
||||||
|
5 ^ 2 -- 25
|
||||||
|
|
||||||
|
-- Booleans
|
||||||
|
not True -- False
|
||||||
|
not False -- True
|
||||||
|
1 == 1 -- True
|
||||||
|
1 /= 1 -- False
|
||||||
|
1 < 10 -- True
|
||||||
|
|
||||||
|
-- Strings and characters
|
||||||
|
"This is a string because it uses double quotes."
|
||||||
|
'a' -- characters in single quotes
|
||||||
|
|
||||||
|
-- Strings can be appended.
|
||||||
|
"Hello " ++ "world!" -- "Hello world!"
|
||||||
|
|
||||||
|
{-- Lists, Tuples, and Records --}
|
||||||
|
|
||||||
|
-- Every element in a list must have the same type.
|
||||||
|
["the", "quick", "brown", "fox"]
|
||||||
|
[1, 2, 3, 4, 5]
|
||||||
|
-- The second example can also be written with two dots.
|
||||||
|
[1..5]
|
||||||
|
|
||||||
|
-- Append lists just like strings.
|
||||||
|
[1..5] ++ [6..10] == [1..10] -- True
|
||||||
|
|
||||||
|
-- To add one item, use "cons".
|
||||||
|
0 :: [1..5] -- [0, 1, 2, 3, 4, 5]
|
||||||
|
|
||||||
|
-- The head and tail of a list are returned as a Maybe. Instead of checking
|
||||||
|
-- every value to see if it's null, you deal with missing values explicitly.
|
||||||
|
List.head [1..5] -- Just 1
|
||||||
|
List.tail [1..5] -- Just [2, 3, 4, 5]
|
||||||
|
List.head [] -- Nothing
|
||||||
|
-- List.functionName means the function lives in the List module.
|
||||||
|
|
||||||
|
-- Every element in a tuple can be a different type, but a tuple has a
|
||||||
|
-- fixed length.
|
||||||
|
("elm", 42)
|
||||||
|
|
||||||
|
-- Access the elements of a pair with the first and second functions.
|
||||||
|
-- (This is a shortcut; we'll come to the "real way" in a bit.)
|
||||||
|
fst ("elm", 42) -- "elm"
|
||||||
|
snd ("elm", 42) -- 42
|
||||||
|
|
||||||
|
-- The empty tuple, or "unit", is sometimes used as a placeholder.
|
||||||
|
-- It is the only value of its type, also called "Unit".
|
||||||
|
()
|
||||||
|
|
||||||
|
-- Records are like tuples but the fields have names. The order of fields
|
||||||
|
-- doesn't matter. Notice that record values use equals signs, not colons.
|
||||||
|
{ x = 3, y = 7 }
|
||||||
|
|
||||||
|
-- Access a field with a dot and the field name.
|
||||||
|
{ x = 3, y = 7 }.x -- 3
|
||||||
|
|
||||||
|
-- Or with an accessor fuction, which is a dot and the field name on its own.
|
||||||
|
.y { x = 3, y = 7 } -- 7
|
||||||
|
|
||||||
|
-- Update the fields of a record. (It must have the fields already.)
|
||||||
|
{ person |
|
||||||
|
name = "George" }
|
||||||
|
|
||||||
|
-- Update multiple fields at once, using the current values.
|
||||||
|
{ particle |
|
||||||
|
position = particle.position + particle.velocity,
|
||||||
|
velocity = particle.velocity + particle.acceleration }
|
||||||
|
|
||||||
|
{-- Control Flow --}
|
||||||
|
|
||||||
|
-- If statements always have an else, and the branches must be the same type.
|
||||||
|
if powerLevel > 9000 then
|
||||||
|
"WHOA!"
|
||||||
|
else
|
||||||
|
"meh"
|
||||||
|
|
||||||
|
-- If statements can be chained.
|
||||||
|
if n < 0 then
|
||||||
|
"n is negative"
|
||||||
|
else if n > 0 then
|
||||||
|
"n is positive"
|
||||||
|
else
|
||||||
|
"n is zero"
|
||||||
|
|
||||||
|
-- Use case statements to pattern match on different possibilities.
|
||||||
|
case aList of
|
||||||
|
[] -> "matches the empty list"
|
||||||
|
[x]-> "matches a list of exactly one item, " ++ toString x
|
||||||
|
x::xs -> "matches a list of at least one item whose head is " ++ toString x
|
||||||
|
-- Pattern matches go in order. If we put [x] last, it would never match because
|
||||||
|
-- x::xs also matches (xs would be the empty list). Matches do not "fall through".
|
||||||
|
-- The compiler will alert you to missing or extra cases.
|
||||||
|
|
||||||
|
-- Pattern match on a Maybe.
|
||||||
|
case List.head aList of
|
||||||
|
Just x -> "The head is " ++ toString x
|
||||||
|
Nothing -> "The list was empty."
|
||||||
|
|
||||||
|
{-- Functions --}
|
||||||
|
|
||||||
|
-- Elm's syntax for functions is very minimal, relying mostly on whitespace
|
||||||
|
-- rather than parentheses and curly brackets. There is no "return" keyword.
|
||||||
|
|
||||||
|
-- Define a function with its name, arguments, an equals sign, and the body.
|
||||||
|
multiply a b =
|
||||||
|
a * b
|
||||||
|
|
||||||
|
-- Apply (call) a function by passing it arguments (no commas necessary).
|
||||||
|
multiply 7 6 -- 42
|
||||||
|
|
||||||
|
-- Partially apply a function by passing only some of its arguments.
|
||||||
|
-- Then give that function a new name.
|
||||||
|
double =
|
||||||
|
multiply 2
|
||||||
|
|
||||||
|
-- Constants are similar, except there are no arguments.
|
||||||
|
answer =
|
||||||
|
42
|
||||||
|
|
||||||
|
-- Pass functions as arguments to other functions.
|
||||||
|
List.map double [1..4] -- [2, 4, 6, 8]
|
||||||
|
|
||||||
|
-- Or write an anonymous function.
|
||||||
|
List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8]
|
||||||
|
|
||||||
|
-- You can pattern match in function definitions when there's only one case.
|
||||||
|
-- This function takes one tuple rather than two arguments.
|
||||||
|
area (width, height) =
|
||||||
|
width * height
|
||||||
|
|
||||||
|
area (6, 7) -- 42
|
||||||
|
|
||||||
|
-- Use curly brackets to pattern match record field names.
|
||||||
|
-- Use let to define intermediate values.
|
||||||
|
volume {width, height, depth} =
|
||||||
|
let
|
||||||
|
area = width * height
|
||||||
|
in
|
||||||
|
area * depth
|
||||||
|
|
||||||
|
volume { width = 3, height = 2, depth = 7 } -- 42
|
||||||
|
|
||||||
|
-- Functions can be recursive.
|
||||||
|
fib n =
|
||||||
|
if n < 2 then
|
||||||
|
1
|
||||||
|
else
|
||||||
|
fib (n - 1) + fib (n - 2)
|
||||||
|
|
||||||
|
List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
|
||||||
|
|
||||||
|
-- Another recursive function (use List.length in real code).
|
||||||
|
listLength aList =
|
||||||
|
case aList of
|
||||||
|
[] -> 0
|
||||||
|
x::xs -> 1 + listLength xs
|
||||||
|
|
||||||
|
-- Function calls happen before any infix operator. Parens indicate precedence.
|
||||||
|
cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
|
||||||
|
-- First degrees is applied to 30, then the result is passed to the trig
|
||||||
|
-- functions, which is then squared, and the addition happens last.
|
||||||
|
|
||||||
|
{-- Types and Type Annotations --}
|
||||||
|
|
||||||
|
-- The compiler will infer the type of every value in your program.
|
||||||
|
-- Types are always uppercase. Read x : T as "x has type T".
|
||||||
|
-- Some common types, which you might see in Elm's REPL.
|
||||||
|
5 : Int
|
||||||
|
6.7 : Float
|
||||||
|
"hello" : String
|
||||||
|
True : Bool
|
||||||
|
|
||||||
|
-- Functions have types too. Read -> as "goes to". Think of the rightmost type
|
||||||
|
-- as the type of the return value, and the others as arguments.
|
||||||
|
not : Bool -> Bool
|
||||||
|
round : Float -> Int
|
||||||
|
|
||||||
|
-- When you define a value, it's good practice to write its type above it.
|
||||||
|
-- The annotation is a form of documentation, which is verified by the compiler.
|
||||||
|
double : Int -> Int
|
||||||
|
double x = x * 2
|
||||||
|
|
||||||
|
-- Function arguments are passed in parentheses.
|
||||||
|
-- Lowercase types are type variables: they can be any type, as long as each
|
||||||
|
-- call is consistent.
|
||||||
|
List.map : (a -> b) -> List a -> List b
|
||||||
|
-- "List dot map has type a-goes-to-b, goes to list of a, goes to list of b."
|
||||||
|
|
||||||
|
-- There are three special lowercase types: number, comparable, and appendable.
|
||||||
|
-- Numbers allow you to use arithmetic on Ints and Floats.
|
||||||
|
-- Comparable allows you to order numbers and strings, like a < b.
|
||||||
|
-- Appendable things can be combined with a ++ b.
|
||||||
|
|
||||||
|
{-- Type Aliases and Union Types --}
|
||||||
|
|
||||||
|
-- When you write a record or tuple, its type already exists.
|
||||||
|
-- (Notice that record types use colon and record values use equals.)
|
||||||
|
origin : { x : Float, y : Float, z : Float }
|
||||||
|
origin =
|
||||||
|
{ x = 0, y = 0, z = 0 }
|
||||||
|
|
||||||
|
-- You can give existing types a nice name with a type alias.
|
||||||
|
type alias Point3D =
|
||||||
|
{ x : Float, y : Float, z : Float }
|
||||||
|
|
||||||
|
-- If you alias a record, you can use the name as a constructor function.
|
||||||
|
otherOrigin : Point3D
|
||||||
|
otherOrigin =
|
||||||
|
Point3D 0 0 0
|
||||||
|
|
||||||
|
-- But it's still the same type, so you can equate them.
|
||||||
|
origin == otherOrigin -- True
|
||||||
|
|
||||||
|
-- By contrast, defining a union type creates a type that didn't exist before.
|
||||||
|
-- A union type is so called because it can be one of many possibilities.
|
||||||
|
-- Each of the possibilities is represented as a "tag".
|
||||||
|
type Direction =
|
||||||
|
North | South | East | West
|
||||||
|
|
||||||
|
-- Tags can carry other values of known type. This can work recursively.
|
||||||
|
type IntTree =
|
||||||
|
Leaf | Node Int IntTree IntTree
|
||||||
|
-- "Leaf" and "Node" are the tags. Everything following a tag is a type.
|
||||||
|
|
||||||
|
-- Tags can be used as values or functions.
|
||||||
|
root : IntTree
|
||||||
|
root =
|
||||||
|
Node 7 Leaf Leaf
|
||||||
|
|
||||||
|
-- Union types (and type aliases) can use type variables.
|
||||||
|
type Tree a =
|
||||||
|
Leaf | Node a (Tree a) (Tree a)
|
||||||
|
-- "The type tree-of-a is a leaf, or a node of a, tree-of-a, and tree-of-a."
|
||||||
|
|
||||||
|
-- Pattern match union tags. The uppercase tags will be matched exactly. The
|
||||||
|
-- lowercase variables will match anything. Underscore also matches anything,
|
||||||
|
-- but signifies that you aren't using it.
|
||||||
|
leftmostElement : Tree a -> Maybe a
|
||||||
|
leftmostElement tree =
|
||||||
|
case tree of
|
||||||
|
Leaf -> Nothing
|
||||||
|
Node x Leaf _ -> Just x
|
||||||
|
Node _ subtree _ -> leftmostElement subtree
|
||||||
|
|
||||||
|
-- That's pretty much it for the language itself. Now let's see how to organize
|
||||||
|
-- and run your code.
|
||||||
|
|
||||||
|
{-- Modules and Imports --}
|
||||||
|
|
||||||
|
-- The core libraries are organized into modules, as are any third-party
|
||||||
|
-- libraries you may use. For large projects, you can define your own modules.
|
||||||
|
|
||||||
|
-- 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.
|
||||||
|
module Name (MyType, myValue) where
|
||||||
|
|
||||||
|
-- One common pattern is to export a union type but not its tags. This is known
|
||||||
|
-- as an "opaque type", and is frequently used in libraries.
|
||||||
|
|
||||||
|
-- Import code from other modules to use it in this one.
|
||||||
|
-- Places Dict in scope, so you can call Dict.insert.
|
||||||
|
import Dict
|
||||||
|
|
||||||
|
-- Imports the Dict module and the Dict type, so your annotations don't have to
|
||||||
|
-- say Dict.Dict. You can still use Dict.insert.
|
||||||
|
import Dict exposing (Dict)
|
||||||
|
|
||||||
|
-- Rename an import.
|
||||||
|
import Graphics.Collage as C
|
||||||
|
|
||||||
|
{-- Ports --}
|
||||||
|
|
||||||
|
-- A port indicates that you will be communicating with the outside world.
|
||||||
|
-- Ports are only allowed in the Main module.
|
||||||
|
|
||||||
|
-- An incoming port is just a type signature.
|
||||||
|
port clientID : Int
|
||||||
|
|
||||||
|
-- An outgoing port has a defintion.
|
||||||
|
port clientOrders : List String
|
||||||
|
port clientOrders = ["Books", "Groceries", "Furniture"]
|
||||||
|
|
||||||
|
-- We won't go into the details, but you set up callbacks in JavaScript to send
|
||||||
|
-- on incoming ports and receive on outgoing ports.
|
||||||
|
|
||||||
|
{-- Command Line Tools --}
|
||||||
|
|
||||||
|
-- Compile a file.
|
||||||
|
$ elm make MyFile.elm
|
||||||
|
|
||||||
|
-- The first time you do this, Elm will install the core libraries and create
|
||||||
|
-- elm-package.json, where information about your project is kept.
|
||||||
|
|
||||||
|
-- The reactor is a server that compiles and runs your files.
|
||||||
|
-- Click the wrench next to file names to enter the time-travelling debugger!
|
||||||
|
$ elm reactor
|
||||||
|
|
||||||
|
-- Experiment with simple expressions in a Read-Eval-Print Loop.
|
||||||
|
$ elm repl
|
||||||
|
|
||||||
|
-- Packages are identified by GitHub username and repo name.
|
||||||
|
-- Install a new package, and record it in elm-package.json.
|
||||||
|
$ elm package install evancz/elm-html
|
||||||
|
|
||||||
|
-- See what changed between versions of a package.
|
||||||
|
$ elm package diff evancz/elm-html 3.0.0 4.0.2
|
||||||
|
-- Elm's package manager enforces semantic versioning, so minor version bumps
|
||||||
|
-- will never break your build!
|
||||||
|
```
|
||||||
|
|
||||||
|
The Elm language is surprisingly small. You can now look through almost any Elm
|
||||||
|
source code and have a rough idea of what is going on. However, the possibilties
|
||||||
|
for error-resistant and easy-to-refactor code are endless!
|
||||||
|
|
||||||
|
Here are some useful resources.
|
||||||
|
|
||||||
|
* The [Elm website](http://elm-lang.org/). Includes:
|
||||||
|
* Links to the [installers](http://elm-lang.org/install)
|
||||||
|
* [Documentation guides](http://elm-lang.org/docs), including the [syntax reference](http://elm-lang.org/docs/syntax)
|
||||||
|
* Lots of helpful [examples](http://elm-lang.org/examples)
|
||||||
|
|
||||||
|
* Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of:
|
||||||
|
* [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default
|
||||||
|
* [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) and its cousin [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), commonly used for missing values or error handling
|
||||||
|
* Data structures like [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
|
||||||
|
* JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
|
||||||
|
|
||||||
|
* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay by Elm's creator with examples on how to organize code into components.
|
||||||
|
|
||||||
|
* The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful.
|
||||||
|
|
||||||
|
* [Scope in Elm](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) and [How to Read a Type Annotation](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). More community guides on the basics of Elm, written for JavaScript developers.
|
||||||
|
|
||||||
|
Go out and write some Elm!
|
@ -177,7 +177,7 @@ is_dog(A) -> false.
|
|||||||
% A guard sequence is either a single guard or a series of guards, separated
|
% A guard sequence is either a single guard or a series of guards, separated
|
||||||
% by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at
|
% by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at
|
||||||
% least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`.
|
% least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`.
|
||||||
is_pet(A) when is_atom(A), (A =:= dog) or (A =:= cat) -> true;
|
is_pet(A) when is_atom(A), (A =:= dog);(A =:= cat) -> true;
|
||||||
is_pet(A) -> false.
|
is_pet(A) -> false.
|
||||||
|
|
||||||
% Warning: not all valid Erlang expressions can be used as guard expressions;
|
% Warning: not all valid Erlang expressions can be used as guard expressions;
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||||
@ -9,8 +9,10 @@ lang: es-es
|
|||||||
---
|
---
|
||||||
|
|
||||||
Brainfuck (con mayúscula sólo al inicio de una oración) es un
|
Brainfuck (con mayúscula sólo al inicio de una oración) es un
|
||||||
lenguaje de programación mínimo, computacionalmente universal
|
lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos.
|
||||||
en tamaño con sólo 8 comandos.
|
|
||||||
|
Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -18,7 +20,7 @@ Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas)
|
|||||||
será ignorado.
|
será ignorado.
|
||||||
|
|
||||||
Brainfuck es representado por un arreglo de 30,000 celdas inicializadas
|
Brainfuck es representado por un arreglo de 30,000 celdas inicializadas
|
||||||
en cero y un apuntador en la celda actual.
|
en cero y un puntero apuntando la celda actual.
|
||||||
|
|
||||||
Existen ocho comandos:
|
Existen ocho comandos:
|
||||||
|
|
||||||
@ -26,7 +28,7 @@ Existen ocho comandos:
|
|||||||
- : Decrementa 1 al valor de la celda actual.
|
- : Decrementa 1 al valor de la celda actual.
|
||||||
> : Mueve el apuntador a la siguiente celda. (a la derecha)
|
> : Mueve el apuntador a la siguiente celda. (a la derecha)
|
||||||
< : Mueve el apuntador a la celda anterior. (a la izquierda)
|
< : Mueve el apuntador a la celda anterior. (a la izquierda)
|
||||||
. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A')
|
. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A')
|
||||||
, : Lee un caracter como input y lo escribe en la celda actual.
|
, : Lee un caracter como input y lo escribe en la celda actual.
|
||||||
[ : Si el valor en la celda actual es cero mueve el apuntador
|
[ : Si el valor en la celda actual es cero mueve el apuntador
|
||||||
hasta el primer ']' que encuentre. Si no es cero sigue a la
|
hasta el primer ']' que encuentre. Si no es cero sigue a la
|
||||||
@ -37,7 +39,7 @@ Existen ocho comandos:
|
|||||||
|
|
||||||
[ y ] forman un while. Obviamente, deben estar balanceados.
|
[ y ] forman un while. Obviamente, deben estar balanceados.
|
||||||
|
|
||||||
Ahora unos ejemplos de programas escritos con brainfuck.
|
Estos son algunos ejemplos de programas escritos con brainfuck.
|
||||||
|
|
||||||
++++++ [ > ++++++++++ < - ] > +++++ .
|
++++++ [ > ++++++++++ < - ] > +++++ .
|
||||||
|
|
||||||
@ -63,7 +65,7 @@ Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un
|
|||||||
cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre
|
cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre
|
||||||
terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.).
|
terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.).
|
||||||
|
|
||||||
Ten en mente que los espacios son sólo para fines de legibilidad.
|
Ten en cuenta que los espacios son sólo para fines de legibilidad.
|
||||||
Es lo mismo escribir el ejemplo de arriba que esto:
|
Es lo mismo escribir el ejemplo de arriba que esto:
|
||||||
,[>+<-]>.
|
,[>+<-]>.
|
||||||
|
|
||||||
@ -81,7 +83,7 @@ hasta la próxima vez. Para resolver este problema también incrementamos la
|
|||||||
celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene
|
celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene
|
||||||
el resultado.
|
el resultado.
|
||||||
```
|
```
|
||||||
Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir
|
Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir
|
||||||
tu propio intérprete de brainfuck o tu propio programa en brainfuck. El
|
tu propio intérprete de brainfuck o tu propio programa en brainfuck. El
|
||||||
intérprete es relativamente sencillo de hacer, pero si eres masoquista,
|
intérprete es relativamente sencillo de hacer, pero si eres masoquista,
|
||||||
intenta construir tu proprio intérprete de brainfuck... en brainfuck.
|
puedes intentar construir tu propio intérprete de brainfuck... en brainfuck.
|
@ -18,11 +18,11 @@ versionar y administrar nuestro código fuente.
|
|||||||
|
|
||||||
## Versionamiento, conceptos.
|
## Versionamiento, conceptos.
|
||||||
|
|
||||||
### Qué es el control de versiones?
|
### ¿Qué es el control de versiones?
|
||||||
El control de versiones es un sistema que guarda todos los cambios realizados en
|
El control de versiones es un sistema que guarda todos los cambios realizados en
|
||||||
uno o varios archivos, a lo largo del tiempo.
|
uno o varios archivos, a lo largo del tiempo.
|
||||||
|
|
||||||
### Versionamiento centralizado vs Versionamiento Distribuido.
|
### Versionamiento centralizado vs versionamiento distribuido.
|
||||||
|
|
||||||
+ El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar
|
+ El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar
|
||||||
archivos.
|
archivos.
|
||||||
@ -33,9 +33,9 @@ uno o varios archivos, a lo largo del tiempo.
|
|||||||
|
|
||||||
[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
|
[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
|
||||||
|
|
||||||
### Por qué usar Git?
|
### ¿Por qué usar Git?
|
||||||
|
|
||||||
* Se puede trabajar sin conexion.
|
* Se puede trabajar sin conexión.
|
||||||
* ¡Colaborar con otros es sencillo!.
|
* ¡Colaborar con otros es sencillo!.
|
||||||
* Derivar, crear ramas del proyecto (aka: Branching) es fácil.
|
* Derivar, crear ramas del proyecto (aka: Branching) es fácil.
|
||||||
* Combinar (aka: Merging)
|
* Combinar (aka: Merging)
|
||||||
@ -47,7 +47,7 @@ uno o varios archivos, a lo largo del tiempo.
|
|||||||
### Repositorio
|
### Repositorio
|
||||||
|
|
||||||
Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
|
Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
|
||||||
comits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
|
commits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
|
||||||
y que sus atributos otorgan acceso al historial del elemento, además de otras
|
y que sus atributos otorgan acceso al historial del elemento, además de otras
|
||||||
cosas.
|
cosas.
|
||||||
|
|
||||||
@ -62,12 +62,12 @@ y mas.
|
|||||||
|
|
||||||
### Directorio de trabajo (componentes del repositorio)
|
### Directorio de trabajo (componentes del repositorio)
|
||||||
|
|
||||||
Es basicamente los directorios y archivos dentro del repositorio. La mayoría de
|
Es básicamente los directorios y archivos dentro del repositorio. La mayoría de
|
||||||
las veces se le llama "directorio de trabajo".
|
las veces se le llama "directorio de trabajo".
|
||||||
|
|
||||||
### Índice (componentes del directorio .git)
|
### Índice (componentes del directorio .git)
|
||||||
|
|
||||||
El índice es el área de inicio en git. Es basicamente la capa que separa el
|
El índice es el área de inicio en git. Es básicamente la capa que separa el
|
||||||
directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores
|
directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores
|
||||||
más poder sobre lo que se envía y se recibe del repositorio.
|
más poder sobre lo que se envía y se recibe del repositorio.
|
||||||
|
|
||||||
|
@ -30,7 +30,7 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto
|
|||||||
// Cada sentencia puede ser terminada con punto y coma ;
|
// Cada sentencia puede ser terminada con punto y coma ;
|
||||||
hazAlgo();
|
hazAlgo();
|
||||||
|
|
||||||
// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente
|
// ... aunque no es necesario, ya que el punto y coma se agrega automáticamente
|
||||||
// cada que se detecta una nueva línea, a excepción de algunos casos.
|
// cada que se detecta una nueva línea, a excepción de algunos casos.
|
||||||
hazAlgo()
|
hazAlgo()
|
||||||
|
|
||||||
@ -109,7 +109,7 @@ null == undefined; // = true
|
|||||||
null === undefined; // false
|
null === undefined; // false
|
||||||
|
|
||||||
// Los Strings funcionan como arreglos de caracteres
|
// Los Strings funcionan como arreglos de caracteres
|
||||||
// Puedes accesar a cada caracter con la función charAt()
|
// Puedes acceder a cada caracter con la función charAt()
|
||||||
"Este es un String".charAt(0); // = 'E'
|
"Este es un String".charAt(0); // = 'E'
|
||||||
|
|
||||||
// ...o puedes usar la función substring() para acceder a pedazos más grandes
|
// ...o puedes usar la función substring() para acceder a pedazos más grandes
|
||||||
@ -186,7 +186,7 @@ miObjeto.miLlave; // = "miValor"
|
|||||||
// agregar nuevas llaves.
|
// agregar nuevas llaves.
|
||||||
miObjeto.miTerceraLlave = true;
|
miObjeto.miTerceraLlave = true;
|
||||||
|
|
||||||
// Si intentas accesar con una llave que aún no está asignada tendrás undefined.
|
// Si intentas acceder con una llave que aún no está asignada tendrás undefined.
|
||||||
miObjeto.miCuartaLlave; // = undefined
|
miObjeto.miCuartaLlave; // = undefined
|
||||||
|
|
||||||
///////////////////////////////////
|
///////////////////////////////////
|
||||||
@ -301,7 +301,7 @@ i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, per
|
|||||||
//inmediatamente", que preveé variables temporales de fugarse al ámbito global
|
//inmediatamente", que preveé variables temporales de fugarse al ámbito global
|
||||||
(function(){
|
(function(){
|
||||||
var temporal = 5;
|
var temporal = 5;
|
||||||
// Podemos accesar al ámbito global asignando al 'objeto global', el cual
|
// Podemos acceder al ámbito global asignando al 'objeto global', el cual
|
||||||
// en un navegador siempre es 'window'. El objeto global puede tener
|
// en un navegador siempre es 'window'. El objeto global puede tener
|
||||||
// un nombre diferente en ambientes distintos, por ejemplo Node.js .
|
// un nombre diferente en ambientes distintos, por ejemplo Node.js .
|
||||||
window.permanente = 10;
|
window.permanente = 10;
|
||||||
@ -321,7 +321,7 @@ function decirHolaCadaCincoSegundos(nombre){
|
|||||||
alert(texto);
|
alert(texto);
|
||||||
}
|
}
|
||||||
setTimeout(interna, 5000);
|
setTimeout(interna, 5000);
|
||||||
// setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos
|
// setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos
|
||||||
// terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos
|
// terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos
|
||||||
// Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene
|
// Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene
|
||||||
// acceso a la variable 'texto' cuando es llamada.
|
// acceso a la variable 'texto' cuando es llamada.
|
||||||
@ -339,7 +339,7 @@ var miObjeto = {
|
|||||||
};
|
};
|
||||||
miObjeto.miFuncion(); // = "¡Hola Mundo!"
|
miObjeto.miFuncion(); // = "¡Hola Mundo!"
|
||||||
|
|
||||||
// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables
|
// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables
|
||||||
// del objeto con la palabra clave 'this'.
|
// del objeto con la palabra clave 'this'.
|
||||||
miObjeto = {
|
miObjeto = {
|
||||||
miString: "¡Hola Mundo!",
|
miString: "¡Hola Mundo!",
|
||||||
@ -401,11 +401,11 @@ var MiConstructor = function(){
|
|||||||
miNuevoObjeto = new MiConstructor(); // = {miNumero: 5}
|
miNuevoObjeto = new MiConstructor(); // = {miNumero: 5}
|
||||||
miNuevoObjeto.miNumero; // = 5
|
miNuevoObjeto.miNumero; // = 5
|
||||||
|
|
||||||
// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una
|
// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a acceder a una
|
||||||
// propiedad en un objeto que no existe en el objeto el intérprete buscará en
|
// propiedad en un objeto que no existe en el objeto el intérprete buscará en
|
||||||
// el prototipo.
|
// el prototipo.
|
||||||
|
|
||||||
// Algunas implementaciones de JavaScript te permiten accesar al prototipo de
|
// Algunas implementaciones de JavaScript te permiten acceder al prototipo de
|
||||||
// un objeto con la propiedad __proto__. Mientras que esto es útil para explicar
|
// un objeto con la propiedad __proto__. Mientras que esto es útil para explicar
|
||||||
// prototipos, no es parte del estándar; veremos formas estándar de usar prototipos
|
// prototipos, no es parte del estándar; veremos formas estándar de usar prototipos
|
||||||
// más adelante.
|
// más adelante.
|
||||||
@ -440,7 +440,7 @@ miPrototipo.sentidoDeLaVida = 43;
|
|||||||
miObjeto.sentidoDeLaVida; // = 43
|
miObjeto.sentidoDeLaVida; // = 43
|
||||||
|
|
||||||
// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no
|
// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no
|
||||||
// existe una forma estándar de accesar al prototipo de un objeto. De todas formas.
|
// existe una forma estándar de acceder al prototipo de un objeto. De todas formas.
|
||||||
// hay dos formas de crear un nuevo objeto con un prototipo dado.
|
// hay dos formas de crear un nuevo objeto con un prototipo dado.
|
||||||
|
|
||||||
// El primer método es Object.create, el cual es una adición reciente a JavaScript,
|
// El primer método es Object.create, el cual es una adición reciente a JavaScript,
|
||||||
@ -476,7 +476,7 @@ typeof miNumero; // = 'number'
|
|||||||
typeof miNumeroObjeto; // = 'object'
|
typeof miNumeroObjeto; // = 'object'
|
||||||
miNumero === miNumeroObjeyo; // = false
|
miNumero === miNumeroObjeyo; // = false
|
||||||
if (0){
|
if (0){
|
||||||
// Este código no se ejecutara porque 0 es false.
|
// Este código no se ejecutará porque 0 es false.
|
||||||
}
|
}
|
||||||
|
|
||||||
// Aún así, los objetos que envuelven y los prototipos por defecto comparten
|
// Aún así, los objetos que envuelven y los prototipos por defecto comparten
|
||||||
|
@ -21,22 +21,22 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
|
|||||||
"llaves": "siempre debe estar entre comillas (ya sean dobles o simples)",
|
"llaves": "siempre debe estar entre comillas (ya sean dobles o simples)",
|
||||||
"numeros": 0,
|
"numeros": 0,
|
||||||
"strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".",
|
"strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".",
|
||||||
"soporta booleanos?": true,
|
"¿soporta booleanos?": true,
|
||||||
"vacios": null,
|
"vacíos": null,
|
||||||
|
|
||||||
"numero grande": 1.2e+100,
|
"numero grande": 1.2e+100,
|
||||||
|
|
||||||
"objetos": {
|
"objetos": {
|
||||||
"comentario": "La mayoria de tu estructura vendra de objetos.",
|
"comentario": "La mayoría de tu estructura vendrá de objetos.",
|
||||||
|
|
||||||
"arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5],
|
"arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5],
|
||||||
|
|
||||||
"otro objeto": {
|
"otro objeto": {
|
||||||
"comentario": "Estas cosas pueden estar anidadas, muy util."
|
"comentario": "Estas cosas pueden estar anidadas, muy útil."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
"tonteria": [
|
"tontería": [
|
||||||
{
|
{
|
||||||
"fuentes de potasio": ["bananas"]
|
"fuentes de potasio": ["bananas"]
|
||||||
},
|
},
|
||||||
@ -50,10 +50,10 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
|
|||||||
|
|
||||||
"estilo alternativo": {
|
"estilo alternativo": {
|
||||||
"comentario": "Mira esto!"
|
"comentario": "Mira esto!"
|
||||||
, "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido"
|
, "posición de la coma": "no importa - mientras este antes del valor, entonces sera válido"
|
||||||
, "otro comentario": "que lindo"
|
, "otro comentario": "qué lindo"
|
||||||
},
|
},
|
||||||
|
|
||||||
"eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer."
|
"eso fue rapido": "Y, estás listo. Ahora sabes todo lo que JSON tiene para ofrecer."
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
213
es-es/latex-es.html.markdown
Normal file
213
es-es/latex-es.html.markdown
Normal file
@ -0,0 +1,213 @@
|
|||||||
|
---
|
||||||
|
language: latex
|
||||||
|
lang: es-es
|
||||||
|
contributors:
|
||||||
|
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
|
||||||
|
- ["Colton Kohnke", "http://github.com/voltnor"]
|
||||||
|
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
|
||||||
|
translators:
|
||||||
|
- ["Mario Pérez", "https://github.com/MarioPerezEsteso"]
|
||||||
|
filename: learn-latex-es.tex
|
||||||
|
---
|
||||||
|
|
||||||
|
```tex
|
||||||
|
% Todas las líneas comentadas comienzan con %
|
||||||
|
% No existen los comentarios multilínea
|
||||||
|
|
||||||
|
% LaTeX NO es un software de procesamiento de texto que cumple con
|
||||||
|
% "Lo que ves es lo que tienes" como MS Word u OpenOffice
|
||||||
|
|
||||||
|
% Todos los comandos de LaTeX comienzan con una contrabarra (\)
|
||||||
|
|
||||||
|
% Los documentos LaTeX comienzan definiendo el tipo de documento que se va a
|
||||||
|
% compilar. Algunos tipos de documentos son libros, informes, presentaciones,
|
||||||
|
% etc. Las opciones para el documento comienzan en los corchetes []. En este
|
||||||
|
% caso, se especifica que queremos utilizar una fuente de tamaño 12pt.
|
||||||
|
\documentclass[12pt]{article}
|
||||||
|
|
||||||
|
% A continuación, definimos los paquetes que utilizará el documento.
|
||||||
|
% Si quieres incluir gráficos, texto coloreado o código fuente de otro lenguaje,
|
||||||
|
% debes extender las funciones de LaTeX. Esto se consigue añadiendo paquetes.
|
||||||
|
% A continuación se incluirán los paquetes float y caption para figuras.
|
||||||
|
\usepackage{caption}
|
||||||
|
\usepackage{float}
|
||||||
|
|
||||||
|
% También podemos definir otras propiedades en el documento
|
||||||
|
\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
|
||||||
|
\date{\today}
|
||||||
|
\title{Learn LaTeX in Y Minutes!}
|
||||||
|
|
||||||
|
% Ahora estamos preparados para comenzar el documento
|
||||||
|
% Todo lo que se encuentre antes de esta línea se llama "El Preámbulo"
|
||||||
|
\begin{document}
|
||||||
|
% Si especificamos el autor, fecha y título, LaTeX creará una página como título
|
||||||
|
% por nosotros
|
||||||
|
\maketitle
|
||||||
|
|
||||||
|
% La mayoría de los artículos de investigación tienen un abstract. Es posible
|
||||||
|
% utilizar comandos predefinidos para ello.
|
||||||
|
% Esto debería aparecer en su orden lógico. Tras el título pero antes de las
|
||||||
|
% secciones principales del cuerpo.
|
||||||
|
% Este comando está disponible en los tipos de documentos article y report.
|
||||||
|
\begin{abstract}
|
||||||
|
Documentación de LaTex escrita en LaTex.
|
||||||
|
\end{abstract}
|
||||||
|
|
||||||
|
% Los comandos de sección son intuitivos.
|
||||||
|
% Todos los títulos de secciones son añadidos automáticamente a la tabla de contenidos.
|
||||||
|
\section{Introducción}
|
||||||
|
Hola, mi nombre es Mario Pérez y estoy traduciendo este documento para aprender LaTex.
|
||||||
|
|
||||||
|
\section{Otra sección}
|
||||||
|
Este es el texto de otra sección. Creo que necesitará una subsección.
|
||||||
|
|
||||||
|
\subsection{Esto es una subsección} % Las subsecciones también son fáciles.
|
||||||
|
Creo que necesitamos otra más.
|
||||||
|
|
||||||
|
\subsubsection{Pitágoras}
|
||||||
|
Mejor ahora.
|
||||||
|
\label{subsec:pitagoras}
|
||||||
|
|
||||||
|
% Utilizando el asterisco podemos decirle a LaTeX que no ponga los números de secciones y subsecciones.
|
||||||
|
% Esto también funciona con otros comandos de LaTeX.
|
||||||
|
\section*{Esto es una sección no numerada}
|
||||||
|
¡No todas las secciones tienen que estar numeradas!
|
||||||
|
|
||||||
|
\section{Algunas notas}
|
||||||
|
LaTeX es generalmente bastante bueno situando el texto donde debe ir. Si una lína \\ necesita \\ ser \\ rota \\ puedes poner \textbackslash\textbackslash en el código fuente. \\
|
||||||
|
|
||||||
|
\section{Listas}
|
||||||
|
Las listas son de las cosas más fáciles de crear en LaTeX. Necesito ir a comprar mañana, así que vamos a crear una lista de la compra.
|
||||||
|
\begin{enumerate} % Esto crea una lista numerada.
|
||||||
|
% \item crea un elemento
|
||||||
|
\item Ensalada.
|
||||||
|
\item 27 sandías.
|
||||||
|
\item Pescado.
|
||||||
|
% podemos incluso sobreescribir el número del ítem usando []
|
||||||
|
\item[cuántos?] Plátanos.
|
||||||
|
|
||||||
|
No es un ítem de la lista, pero sigue siendo parte de la enumeración.
|
||||||
|
|
||||||
|
\end{enumerate} % Todos los contextos deben tener un final.
|
||||||
|
|
||||||
|
\section{Matemáticas}
|
||||||
|
|
||||||
|
Uno de los usos principales de LaTeX es la producción de artículos académicos o técnicos. Normalmente relacionados con la ciencia y las matemáticas. Debido a esto, necesitamos poder añadir símbolos especiales a nuestro artículo.\\
|
||||||
|
|
||||||
|
En matemáticas hay muchos símbolos. Más de los que podemos encontrar en un teclado. Flechas o letras por nombrar un par.\\
|
||||||
|
|
||||||
|
Algunos símbolos juegan un papel fundamental en muchos artículos de investigación matemática. Así es como se establece que todo Y pertenece a X: $\forall$ x $\in$ X. \\
|
||||||
|
He necesitado añadir el signo $ antes de los símbolos. Esto se debe a que cuando escribimos, estamos en modo texto. Sin embargo, los símbolos solo pueden utilizarse en modo matemático, al cual se entra con el signo $.
|
||||||
|
% Lo opuesto también se cumple. Una variable también puede ser mostrada en modo matemático, al que también se puede entrar con \[\]
|
||||||
|
|
||||||
|
\[a^2 + b^2 = c^2 \]
|
||||||
|
|
||||||
|
Mi letra griega favorita es $\xi$. También me gustan $\beta$, $\gamma$ y $\sigma$.
|
||||||
|
Todavía no he encontrado una letra griega que LaTeX no conozca.
|
||||||
|
|
||||||
|
Los operadores son también una parte esencial de un documento matemático:
|
||||||
|
funciones trigonométricas ($\sin$, $\cos$, $\tan$), logaritmos y exponenciales ($\log$, $\exp$), límites ($\lim$), etc. tienen comandos predefinidos en LaTeX.
|
||||||
|
|
||||||
|
Vamos a escribir una ecuación para ver cómo se hace: \\
|
||||||
|
|
||||||
|
$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
|
||||||
|
|
||||||
|
Las fracciones (numeradores-denominadores) pueden escribirse de la siguiente forma:
|
||||||
|
|
||||||
|
% 10 / 7
|
||||||
|
$^{10}/_{7}$
|
||||||
|
|
||||||
|
% Las fracciones relativamente complejas pueden escribirse como
|
||||||
|
% \frac{numerador}{denominador}
|
||||||
|
$\frac{n!}{k!(n - k)!}$ \\
|
||||||
|
|
||||||
|
También podemos insertar ecuaciones en un contexto de ecuación.
|
||||||
|
|
||||||
|
% Mostrar matemáticas en el contexto de ecuaciones
|
||||||
|
\begin{equation} % entra en modo matemático
|
||||||
|
c^2 = a^2 + b^2.
|
||||||
|
\label{eq:pitagoras} % para referencias
|
||||||
|
\end{equation} % Todos los contextos deben tener un final.
|
||||||
|
|
||||||
|
Podemos referenciar nuestra nueva ecuación.
|
||||||
|
Ecuación ~\ref{eq:pythagoras} también se conoce como el Teorema de Pitágoras, el cual también se encuentra en la sección ~\ref{subsec:pythagoras}. Muchas cosas pueden ser etiquetadas: figures, equations, sections, etc.
|
||||||
|
|
||||||
|
Los sumatorios e integrales son escritor son los comandos sum e int:
|
||||||
|
|
||||||
|
% Algunos compiladores de LaTeX se quejarán si hay líneas en blanco
|
||||||
|
% En un contexto de ecuación.
|
||||||
|
\begin{equation}
|
||||||
|
\sum_{i=0}^{5} f_{i}
|
||||||
|
\end{equation}
|
||||||
|
\begin{equation}
|
||||||
|
\int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
|
||||||
|
\end{equation}
|
||||||
|
|
||||||
|
\section{Figuras}
|
||||||
|
|
||||||
|
Vamos a insertar una figura. Situarla puede ser algo complicado.
|
||||||
|
|
||||||
|
\begin{figure}[H] % H aquí establece la situación de la figura.
|
||||||
|
\centering % centra la figura en la página
|
||||||
|
% Inserta una figura escalada por 0.8 el ancho de la página.
|
||||||
|
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
|
||||||
|
% La línea anterior ha sido comentada para poder compilar este archivo. Por favor, usa tu imaginación.
|
||||||
|
\caption{Triángulo con lados $a$, $b$, $c$}
|
||||||
|
\label{fig:right-triangle}
|
||||||
|
\end{figure}
|
||||||
|
|
||||||
|
\subsection{Tablas}
|
||||||
|
También podemos insertar tablas de la misma manera que las figuras.
|
||||||
|
|
||||||
|
\begin{table}[H]
|
||||||
|
\caption{Título para la tabla.}
|
||||||
|
% los argumentos en {} describen cómo cada fila va a ser representada.
|
||||||
|
\begin{tabular}{c|cc}
|
||||||
|
Número & Nombre & Apellido \\
|
||||||
|
\hline % una línea horizontal
|
||||||
|
1 & Biggus & Dickus \\
|
||||||
|
2 & Monty & Python
|
||||||
|
\end{tabular}
|
||||||
|
\end{table}
|
||||||
|
|
||||||
|
% \section{Hyperlinks} % En construcción
|
||||||
|
|
||||||
|
\section{Haciendo que LaTeX no compile algo (por ejemplo, código fuente)}
|
||||||
|
Digamos que queremos incluir código fuente dentro de nuestro documento LaTex. En ese caso, debemos indicarle a LaTeX que no trate de compilarlo y simplemente lo muestre en el documento. Esto lo realizamos en el contexto verbatim.
|
||||||
|
|
||||||
|
% Hay otros paquetes para esta misma tarea, pero verbatim es el más básico.
|
||||||
|
\begin{verbatim}
|
||||||
|
print("Hola Mundo!")
|
||||||
|
a%b; % Podemos usar los signos % en verbatim.
|
||||||
|
aleatorio = 4; # Número aleatorio
|
||||||
|
\end{verbatim}
|
||||||
|
|
||||||
|
\section{Compilación}
|
||||||
|
|
||||||
|
Ahora mismo te estarás preguntando cómo compilar este fabuloso documento y obtener un documento PDF.\\
|
||||||
|
Para obtener el documento final utilizando LaTeX hay que seguir los siguientes pasos:
|
||||||
|
\begin{enumerate}
|
||||||
|
\item Escribe el documento en texto plano.
|
||||||
|
\item Compila el código para producir un PDF.
|
||||||
|
Los pasos de compilación serán algo parecido a esto (en Linux): \\
|
||||||
|
\begin{verbatim}
|
||||||
|
$pdflatex learn-latex.tex learn-latex.pdf
|
||||||
|
\end{verbatim}
|
||||||
|
\end{enumerate}
|
||||||
|
|
||||||
|
Un gran número de editores LaTeX combinan ambos pasos para que sea más sencillo obtener el documento.
|
||||||
|
|
||||||
|
Escribe toda la información de formato en el paso 1 y con el paso 2 obtendrás el documento que has definido en el paso anterior.
|
||||||
|
|
||||||
|
\section{End}
|
||||||
|
|
||||||
|
Esto es todo por ahora.
|
||||||
|
|
||||||
|
% fin del documento
|
||||||
|
\end{document}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Más información sobre LaTeX
|
||||||
|
|
||||||
|
* El wikilibro LaTeX: [https://es.wikibooks.org/wiki/Manual_de_LaTeX](https://es.wikibooks.org/wiki/Manual_de_LaTeX)
|
||||||
|
* Un tutorial real: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
|
@ -11,7 +11,7 @@ lang: es-es
|
|||||||
Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta
|
Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta
|
||||||
fácilmente a HTML (y, actualmente, otros formatos también).
|
fácilmente a HTML (y, actualmente, otros formatos también).
|
||||||
|
|
||||||
¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
|
¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
|
||||||
|
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
@ -44,7 +44,7 @@ Esto es un h2
|
|||||||
-------------
|
-------------
|
||||||
|
|
||||||
<!-- Estilos para texto plano -->
|
<!-- Estilos para texto plano -->
|
||||||
<!-- El texto puede ser fácilmente estilizaedo con italicas, negritas o tachado
|
<!-- El texto puede ser fácilmente estilizado con italicas, negritas o tachado
|
||||||
usando markdown -->
|
usando markdown -->
|
||||||
|
|
||||||
*Este texto está en itálicas.*
|
*Este texto está en itálicas.*
|
||||||
@ -62,7 +62,7 @@ Markdown en Github, también tenemos: -->
|
|||||||
|
|
||||||
~~Este texto está tachado.~~
|
~~Este texto está tachado.~~
|
||||||
|
|
||||||
<!-- Los párrafos son una o múltuples líneas de texto adyacentes separadas por
|
<!-- Los párrafos son una o múltiples líneas de texto adyacentes separadas por
|
||||||
una o múltiples líneas en blanco-->
|
una o múltiples líneas en blanco-->
|
||||||
|
|
||||||
Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido?
|
Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido?
|
||||||
|
825
es-es/php-es.html.markdown
Normal file
825
es-es/php-es.html.markdown
Normal file
@ -0,0 +1,825 @@
|
|||||||
|
---
|
||||||
|
language: PHP
|
||||||
|
contributors:
|
||||||
|
- ["Malcolm Fell", "http://emarref.net/"]
|
||||||
|
- ["Trismegiste", "https://github.com/Trismegiste"]
|
||||||
|
translators:
|
||||||
|
- ["Mario Pérez", "https://github.com/MarioPerezEsteso"]
|
||||||
|
lang: es-es
|
||||||
|
filename: learnphp-es.php
|
||||||
|
---
|
||||||
|
|
||||||
|
Este documento explica el funcionamiento de PHP 5+.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php // El código PHP debe estar dentro de etiquetas <?php
|
||||||
|
|
||||||
|
// Si tu fichero php solo contiene código php, es una buena práctica
|
||||||
|
// omitir la etiqueta de cierre php para prevenir salidas acidentales.
|
||||||
|
|
||||||
|
// Dos barras comienzan un comentario de una línea.
|
||||||
|
|
||||||
|
# También lo hará una almohadilla, pero // es más común
|
||||||
|
|
||||||
|
/*
|
||||||
|
Escribir texto entre una barra-asterisco y asterisco-barra
|
||||||
|
crea un comentario multilínea.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Utiliza "echo" o "print" para imprimir por pantalla
|
||||||
|
print('Hola '); // Imprime "Hola " sin salto de línea
|
||||||
|
|
||||||
|
// () son opcionales para print y echo
|
||||||
|
echo "Mundo\n"; // Imprime "Mundo" con un salto de línea
|
||||||
|
// (todas las sentencias deben finalizar con un punto y coma)
|
||||||
|
|
||||||
|
// Cualquier cosa fuera de las etiquetas <?php se imprime automáticamente
|
||||||
|
?>
|
||||||
|
¡Hola Mundo de nuevo!
|
||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
/************************************
|
||||||
|
* Tipos y variables
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Las variables comienzan con el símbolo $.
|
||||||
|
// Una variable válida comienza con una letra o guión bajo,
|
||||||
|
// seguida de cualquier cantidad de letras, números o guiones bajos.
|
||||||
|
|
||||||
|
// Las variables booleanas no distinguen entre mayúsculas o minúsculas
|
||||||
|
$boolean = true; // o TRUE o True
|
||||||
|
$boolean = false; // o FALSE o False
|
||||||
|
|
||||||
|
// Enteros
|
||||||
|
$int1 = 12; // => 12
|
||||||
|
$int2 = -12; // => -12
|
||||||
|
$int3 = 012; // => 10 (un 0 al comienzo declara un número octal)
|
||||||
|
$int4 = 0x0F; // => 15 (un 0x al comienzo declara un hexadecimal)
|
||||||
|
|
||||||
|
// Floats (también conocidos como doubles)
|
||||||
|
$float = 1.234;
|
||||||
|
$float = 1.2e3;
|
||||||
|
$float = 7E-10;
|
||||||
|
|
||||||
|
// Eliminar variable
|
||||||
|
unset($int1);
|
||||||
|
|
||||||
|
// Operaciones aritméticas
|
||||||
|
$suma = 1 + 1; // 2
|
||||||
|
$diferencia = 2 - 1; // 1
|
||||||
|
$producto = 2 * 2; // 4
|
||||||
|
$cociente = 2 / 1; // 2
|
||||||
|
|
||||||
|
// Operaciones aritméticas de escritura rápida
|
||||||
|
$numero = 0;
|
||||||
|
$numero += 1; // Incrementa $numero en 1
|
||||||
|
echo $numero++; // Imprime 1 (incremento después la evaluación)
|
||||||
|
echo ++$numero; // Imprime 3 (incremento antes de la evaluación)
|
||||||
|
$numero /= $float; // Divide y asigna el cociente a $numero
|
||||||
|
|
||||||
|
// Las cadenas de caracteres deben declararse entre comillas simples
|
||||||
|
$sgl_quotes = '$String'; // => '$String'
|
||||||
|
|
||||||
|
// Evita utilizar comillas dobles excepto para embeber otras variables
|
||||||
|
$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
|
||||||
|
|
||||||
|
// Los caracteres especiales solo son válidos entre comillas dobles
|
||||||
|
$escaped = "Esto contiene \t un caracter tabulador.";
|
||||||
|
$unescaped = 'Esto solo contiene una barra y una t: \t';
|
||||||
|
|
||||||
|
// Rodea una variable entre corchetes si es necesario
|
||||||
|
$dinero = "Tengo $${numero} en el banco.";
|
||||||
|
|
||||||
|
// Desde PHP 5.3, los nowdocs pueden ser utilizados para multilíneas no interpoladas
|
||||||
|
$nowdoc = <<<'END'
|
||||||
|
Multi line
|
||||||
|
string
|
||||||
|
END;
|
||||||
|
|
||||||
|
// Heredocs interpola cadenas de caracteres
|
||||||
|
$heredoc = <<<END
|
||||||
|
Multi line
|
||||||
|
$sgl_quotes
|
||||||
|
END;
|
||||||
|
|
||||||
|
// La concatenación de cadenas de caracteres se realiza con .
|
||||||
|
echo 'Esta cadena de caracteres ' . 'está concatenada';
|
||||||
|
|
||||||
|
// Las cadenas de caracteres pueden ser pasadas como parámetros en un echo
|
||||||
|
echo 'Multiples', 'Parametros', 'Validos'; // Devuelve 'MultiplesParametrosValidos'
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Constantes
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Una constante se define utilizando define()
|
||||||
|
// y nunca puede ser cambiada en tiempo de ejecución
|
||||||
|
|
||||||
|
// un nombre válido para una constante debe comenzar con una letra o guión bajo,
|
||||||
|
// seguido por cualquier número de letras, números o guiones bajos.
|
||||||
|
define("FOO", "algo");
|
||||||
|
|
||||||
|
// el acceso a una constante se puede realizar llamando a la variable elegida sin un símbolo de $
|
||||||
|
echo FOO; // Devuelve 'algo'
|
||||||
|
echo 'Esto imprime '.FOO; // Devuelve 'Esto imprime algo'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Arrays
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Todos los arrays en PHP son asociativos (hashmaps),
|
||||||
|
|
||||||
|
// Los arrays asociativos son conocidos como hashmaps en algunos lenguajes.
|
||||||
|
|
||||||
|
// Funciona con todas las versiones de php
|
||||||
|
$asociativo = array('Uno' => 1, 'Dos' => 2, 'Tres' => 3);
|
||||||
|
|
||||||
|
// PHP 5.4 introdujo una nueva sintaxis
|
||||||
|
$asociativo = ['Uno' => 1, 'Dos' => 2, 'Tres' => 3];
|
||||||
|
|
||||||
|
echo $asociativo['Uno']; // imprime 1
|
||||||
|
|
||||||
|
// Lista literales implícitamente asignados con claves enteras
|
||||||
|
$array = ['Uno', 'Dos', 'Tres'];
|
||||||
|
echo $array[0]; // => "Uno"
|
||||||
|
|
||||||
|
// Añadir un elemento al final de un array
|
||||||
|
$array[] = 'Cuatro';
|
||||||
|
// o
|
||||||
|
array_push($array, 'Cinco');
|
||||||
|
|
||||||
|
// Eliminar un elemento de un array
|
||||||
|
unset($array[3]);
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Salidas por pantalla
|
||||||
|
*/
|
||||||
|
|
||||||
|
echo('¡Hola Mundo!');
|
||||||
|
// Imprime ¡Hola Mundo! en stdout.
|
||||||
|
// Stdout es la página web si se está ejecutando en un navegador.
|
||||||
|
|
||||||
|
print('!Hola Mundo!'); // Es lo mismo que echo
|
||||||
|
|
||||||
|
// No es necesario el paréntesis en echo y print
|
||||||
|
echo '¡Hola Mundo!';
|
||||||
|
print '¡Hola Mundo!';
|
||||||
|
|
||||||
|
$parrafo = 'parrafo';
|
||||||
|
|
||||||
|
echo 100; // Haz echo de escalares directamente
|
||||||
|
echo $parrafo; // o de variables
|
||||||
|
|
||||||
|
// Si las etiquetas cortas estás configuradas y tu versión de PHP es
|
||||||
|
// la 5.4.0 o superior, puede utilizar la sintaxis abreviada de echo
|
||||||
|
?>
|
||||||
|
<p><?= $parrafo?></p>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$x = 1;
|
||||||
|
$y = 2;
|
||||||
|
$x = $y; // $x ahora contiene el mismo valor que $y
|
||||||
|
$z = &$y;
|
||||||
|
// $z contiene ahora una referencia a $y. Un cambio en el valor de
|
||||||
|
// $z cambiará también el valor de $y, y viceversa.
|
||||||
|
// $x sin embargo, tendrá el valor original de $y
|
||||||
|
|
||||||
|
echo $x; // => 2
|
||||||
|
echo $z; // => 2
|
||||||
|
$y = 0;
|
||||||
|
echo $x; // => 2
|
||||||
|
echo $z; // => 0
|
||||||
|
|
||||||
|
// Dump muestra el tipo y valor de una variable en stdout
|
||||||
|
var_dump($z); // imprime int(0)
|
||||||
|
|
||||||
|
// Para mostrar el valor de una variable en un formato legible para humanos
|
||||||
|
print_r($array); // imprime: Array ( [0] => Uno [1] => Dos [2] => Tres )
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Lógica
|
||||||
|
*/
|
||||||
|
$a = 0;
|
||||||
|
$b = '0';
|
||||||
|
$c = '1';
|
||||||
|
$d = '1';
|
||||||
|
|
||||||
|
// assert lanza una advertencia si su argumento no es verdadero
|
||||||
|
|
||||||
|
// Estas comparaciones siempre serán verdaderas, incluso si los tipos no son los mismos.
|
||||||
|
assert($a == $b); // igualdad
|
||||||
|
assert($c != $a); // desigualdad
|
||||||
|
assert($c <> $a); // desigualdad alternativa
|
||||||
|
assert($a < $c);
|
||||||
|
assert($c > $b);
|
||||||
|
assert($a <= $b);
|
||||||
|
assert($c >= $d);
|
||||||
|
|
||||||
|
// Los siguiente solo será verdadero si los valores coinciden y son del mismo tipo.
|
||||||
|
assert($c === $d);
|
||||||
|
assert($a !== $d);
|
||||||
|
assert(1 === '1');
|
||||||
|
assert(1 !== '1');
|
||||||
|
|
||||||
|
// Operador 'Spaceship' (desde PHP 7)
|
||||||
|
// Devuelve 0 si ambos valores son iguales
|
||||||
|
// Devuelve 1 si el valor de la izquierda es mayor
|
||||||
|
// Devuelve -1 si el valor de la derecha es mayor
|
||||||
|
|
||||||
|
$a = 100;
|
||||||
|
$b = 1000;
|
||||||
|
|
||||||
|
echo $a <=> $a; // 0 porque son iguales
|
||||||
|
echo $a <=> $b; // -1 porque $a < $b
|
||||||
|
echo $b <=> $a; // 1 porque $b > $a
|
||||||
|
|
||||||
|
// Las variables pueden ser convertidas entre tipos, dependiendo de su uso.
|
||||||
|
|
||||||
|
$entero = 1;
|
||||||
|
echo $entero + $entero; // => 2
|
||||||
|
|
||||||
|
$string = '1';
|
||||||
|
echo $string + $string; // => 2 (los strings son convertidos a enteros)
|
||||||
|
|
||||||
|
$string = 'uno';
|
||||||
|
echo $string + $string; // => 0
|
||||||
|
// Muestra un 0 porque el operador + no puede convertir la cadena de caracteres 'uno' a un número
|
||||||
|
|
||||||
|
// La conversión de tipos puede ser utilizada para tratar a una variable como otro tipo
|
||||||
|
|
||||||
|
$boolean = (boolean) 1; // => true
|
||||||
|
|
||||||
|
$cero = 0;
|
||||||
|
$boolean = (boolean) $cero; // => false
|
||||||
|
|
||||||
|
// También hay funciones dedicadas a la conversión de tipos
|
||||||
|
$entero = 5;
|
||||||
|
$string = strval($entero);
|
||||||
|
|
||||||
|
$var = null; // Valor nulo
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Estructuras de control
|
||||||
|
*/
|
||||||
|
|
||||||
|
if (true) {
|
||||||
|
print 'He sido imprimido';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false) {
|
||||||
|
print 'Yo no';
|
||||||
|
} else {
|
||||||
|
print 'He sido imprimido';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false) {
|
||||||
|
print 'No se imprime';
|
||||||
|
} elseif(true) {
|
||||||
|
print 'Sí se imprime';
|
||||||
|
}
|
||||||
|
|
||||||
|
// operador ternario
|
||||||
|
print (false ? 'No se imprime' : 'Sí se imprime');
|
||||||
|
|
||||||
|
// atajo para el operador ternario desde PHP 5.3
|
||||||
|
// equivalente de "$x ? $x : 'Sí'""
|
||||||
|
$x = false;
|
||||||
|
print($x ?: 'Sí');
|
||||||
|
|
||||||
|
// operador 'no definido' desde php 7
|
||||||
|
$a = null;
|
||||||
|
$b = 'Imprime';
|
||||||
|
echo $a ?? 'a no está definido'; // imprime 'a no está definido'
|
||||||
|
echo $b ?? 'b no está definido'; // imprime 'Imprime'
|
||||||
|
|
||||||
|
|
||||||
|
$x = 0;
|
||||||
|
if ($x === '0') {
|
||||||
|
print 'No imprime';
|
||||||
|
} elseif($x == '1') {
|
||||||
|
print 'No imprime';
|
||||||
|
} else {
|
||||||
|
print 'Imprime';
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Esta sintaxis alternativa se utiliza para plantillas:
|
||||||
|
?>
|
||||||
|
|
||||||
|
<?php if ($x): ?>
|
||||||
|
Esto se muestra si la evaluación es verdadera.
|
||||||
|
<?php else: ?>
|
||||||
|
En otro caso, se muestra esto.
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Utiliza el switch para tener algo más de lógica.
|
||||||
|
switch ($x) {
|
||||||
|
case '0':
|
||||||
|
print 'Switch does type coercion';
|
||||||
|
break; // Debes incluir un break para no seguir con los casos 'Dos' y 'Tres'
|
||||||
|
case 'Dos':
|
||||||
|
case 'Tres':
|
||||||
|
// Hacer algo si la variables es 'Dos' o 'Tres'
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// Hacer algo por defecto
|
||||||
|
}
|
||||||
|
|
||||||
|
// Los bucles While, do...while y for te serán familiares
|
||||||
|
$i = 0;
|
||||||
|
while ($i < 5) {
|
||||||
|
echo $i++;
|
||||||
|
}; // Imprime "01234"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$i = 0;
|
||||||
|
do {
|
||||||
|
echo $i++;
|
||||||
|
} while ($i < 5); // Imprime "01234"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
for ($x = 0; $x < 10; $x++) {
|
||||||
|
echo $x;
|
||||||
|
} // Imprime "0123456789"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$ruedas = ['bicicleta' => 2, 'coche' => 4];
|
||||||
|
|
||||||
|
// Los bucles foreach pueden iterar por arrays
|
||||||
|
foreach ($ruedas as $numero_ruedas) {
|
||||||
|
echo $numero_ruedas;
|
||||||
|
} // Imprime "24"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
// También se puede iterar sobre las claves, así como sobre los valores
|
||||||
|
foreach ($ruedas as $vehiculo => $numero_ruedas) {
|
||||||
|
echo "Un $vehiculo tiene $numero_ruedas ruedas";
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$i = 0;
|
||||||
|
while ($i < 5) {
|
||||||
|
if ($i === 3) {
|
||||||
|
break; // Sale fuera del bucle while
|
||||||
|
}
|
||||||
|
echo $i++;
|
||||||
|
} // Imprime "012"
|
||||||
|
|
||||||
|
for ($i = 0; $i < 5; $i++) {
|
||||||
|
if ($i === 3) {
|
||||||
|
continue; // Se salta esta iteración del bucle
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
} // Imprime "0124"
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Funciones
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Define una función con "function":
|
||||||
|
function mi_funcion () {
|
||||||
|
return 'Hola';
|
||||||
|
}
|
||||||
|
|
||||||
|
echo mi_funcion(); // => "Hola"
|
||||||
|
|
||||||
|
// Un nombre válido de función comienza con una letra o guión bajo, seguido de cualquier
|
||||||
|
// número de letras, números o guiones bajos.
|
||||||
|
|
||||||
|
function anadir ($x, $y = 1) { // $y es opcional y por defecto es 1
|
||||||
|
$resultado = $x + $y;
|
||||||
|
return $resultado;
|
||||||
|
}
|
||||||
|
|
||||||
|
echo anadir(4); // => 5
|
||||||
|
echo anadir(4, 2); // => 6
|
||||||
|
|
||||||
|
// $resultado no es accesible fuera de la función
|
||||||
|
// print $resultado; // Devuelve una advertencia.
|
||||||
|
|
||||||
|
// Desde PHP 5.3 se pueden declarar funciones anónimas
|
||||||
|
$inc = function ($x) {
|
||||||
|
return $x + 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
echo $inc(2); // => 3
|
||||||
|
|
||||||
|
function foo ($x, $y, $z) {
|
||||||
|
echo "$x - $y - $z";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Las funciones pueden devolver funciones
|
||||||
|
function bar ($x, $y) {
|
||||||
|
// Utiliza 'use' para meter variables de fuera de la función
|
||||||
|
return function ($z) use ($x, $y) {
|
||||||
|
foo($x, $y, $z);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$bar = bar('A', 'B');
|
||||||
|
$bar('C'); // Imprime "A - B - C"
|
||||||
|
|
||||||
|
// Puedes llamar a funciones utilizando cadenas de caracteres
|
||||||
|
$nombre_funcion = 'add';
|
||||||
|
echo $nombre_funcion(1, 2); // => 3
|
||||||
|
// Es útil para determinarl qué función ejecutar.
|
||||||
|
// O, utiliza call_user_func(callable $callback [, $parameter [, ... ]]);
|
||||||
|
|
||||||
|
|
||||||
|
// Puedes obtener todos los parámetros pasados a una función
|
||||||
|
function parametros() {
|
||||||
|
$numero_argumentos = func_num_args();
|
||||||
|
if ($numero_argumentos > 0) {
|
||||||
|
echo func_get_arg(0) . ' | ';
|
||||||
|
}
|
||||||
|
$args_array = func_get_args();
|
||||||
|
foreach ($args_array as $key => $arg) {
|
||||||
|
echo $key . ' - ' . $arg . ' | ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
parametros('Hola', 'Mundo'); // Hola | 0 - Hola | 1 - Mundo |
|
||||||
|
|
||||||
|
// Desde PHP 5.6 se puede obtener un número variable de argumentos
|
||||||
|
function variable($palabra, ...$lista) {
|
||||||
|
echo $palabra . " || ";
|
||||||
|
foreach ($lista as $item) {
|
||||||
|
echo $item . ' | ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
variable("Separa", "Hola", "Mundo") // Separa || Hola | Mundo |
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Includes
|
||||||
|
*/
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// Los ficheros PHP incluidos deben comenzar también con la etiqueta de <?php
|
||||||
|
|
||||||
|
include 'mi-fichero.php';
|
||||||
|
// El código de mi-fichero.php ya está disponible en el entorno actual.
|
||||||
|
// Si el fichero no puede ser incluido (por ejemplo porque no se ha encontrado),
|
||||||
|
// se muestra una advertencia.
|
||||||
|
|
||||||
|
include_once 'mi-fichero.php';
|
||||||
|
// Si el código del fichero mi-fichero.php ya ha sido incluido, ya no se
|
||||||
|
// incluirá de nuevo. Este previene errores por múltiples declaraciones.
|
||||||
|
|
||||||
|
require 'mi-fichero.php';
|
||||||
|
require_once 'mi-fichero.php';
|
||||||
|
// Es lo mismo que el include(), pero require() causará un error fatal si el archivo
|
||||||
|
// no ha podido ser incluido.
|
||||||
|
|
||||||
|
// Contenido de mi-include.php:
|
||||||
|
<?php
|
||||||
|
|
||||||
|
return 'Cualquier cosa.';
|
||||||
|
// acabar archivo
|
||||||
|
|
||||||
|
// Los include y require también pueden devolver un valor.
|
||||||
|
$valor = include 'mi-include.php';
|
||||||
|
|
||||||
|
// Los archivos son incluidos en función de la ruta data o, si ninguna ruta es
|
||||||
|
// especificada se utilizará la directiva de configuración de include_path. Si el
|
||||||
|
// fichero no se encuentra en el include_path, include comprobará la ruta del código
|
||||||
|
// que lo llama antes de fallar.
|
||||||
|
/* */
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Clases
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Las clases son definidas con la palabra clave class
|
||||||
|
|
||||||
|
class MiClase
|
||||||
|
{
|
||||||
|
const MI_CONSTANTE = 'valor'; // Una constante
|
||||||
|
|
||||||
|
static $staticVar = 'static';
|
||||||
|
|
||||||
|
// Las variables estáticas y su visibilidad
|
||||||
|
public static $publicStaticVar = 'publicStatic';
|
||||||
|
// Accesible solo dentro de su clase
|
||||||
|
private static $privateStaticVar = 'privateStatic';
|
||||||
|
// Accesible desde la clase y las subclases
|
||||||
|
protected static $protectedStaticVar = 'protectedStatic';
|
||||||
|
|
||||||
|
// Las propiedades deben declarar su visibilidad
|
||||||
|
public $propiedad = 'public';
|
||||||
|
public $instanceProp;
|
||||||
|
protected $prot = 'protected'; // Accesible desde la clase y las subclases
|
||||||
|
private $priv = 'private'; // Accesible solo desde la clase
|
||||||
|
|
||||||
|
// Crear un constructor con __construct
|
||||||
|
public function __construct($instanceProp) {
|
||||||
|
// Accede a las variables de la instancia con $this
|
||||||
|
$this->instanceProp = $instanceProp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Los métodos son declarados como funciones dentro de una clase
|
||||||
|
public function miMetodo()
|
||||||
|
{
|
||||||
|
print 'MiClase';
|
||||||
|
}
|
||||||
|
|
||||||
|
// la palabra clave final hará una función no sobreescribible
|
||||||
|
final function noMePuedesSobreEscribir()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Declarar propiedades de clase o métodos como estáticos los hace accesibles sin
|
||||||
|
* necesidad de instanciar la clase. Una propiedad declarada como estática no
|
||||||
|
* puede ser accedida mediante una instancia de la clase, pero sí mediante un
|
||||||
|
* método estático.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public static function miMetodoEstatico()
|
||||||
|
{
|
||||||
|
print 'Soy estático';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Las constantes de una clase siempre pueden ser accedidas estáticamente
|
||||||
|
echo MiClase::MI_CONSTANTE; // Muestra 'valor';
|
||||||
|
|
||||||
|
echo MiClase::$staticVar; // Muestra 'static';
|
||||||
|
MiClase::miMetodoEstatico(); // Muestra 'Soy estático';
|
||||||
|
|
||||||
|
// Instancia una clase usando new
|
||||||
|
$mi_clase = new MiClase('Una instancia');
|
||||||
|
// Los paréntesis son opcionales si no se pasa ningún argumento.
|
||||||
|
|
||||||
|
// Accede a los miembros de una clase utilizando ->
|
||||||
|
echo $mi_clase->propiedad; // => "public"
|
||||||
|
echo $mi_clase->instanceProp; // => "Una instancia"
|
||||||
|
$mi_clase->miMetodo(); // => "MiClase"
|
||||||
|
|
||||||
|
|
||||||
|
// Extender clases utilizando "extends"
|
||||||
|
class MiOtraClase extends MiClase
|
||||||
|
{
|
||||||
|
function imprimePropiedadProtegida()
|
||||||
|
{
|
||||||
|
echo $this->prot;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sobreescribe un método
|
||||||
|
function miMetodo()
|
||||||
|
{
|
||||||
|
parent::miMetodo();
|
||||||
|
print ' > MiOtraClase';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$mi_otra_clase = new MiOtraClase('Propiedad de instancia');
|
||||||
|
$mi_otra_clase->imprimePropiedadProtegida(); // => Imprime "protected"
|
||||||
|
$mi_otra_clase->miMetodo(); // Imprime "MiClase > MiOtraClase"
|
||||||
|
|
||||||
|
final class NoMePuedesExtender
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// Puedes utilizar "métodos mágicos" para crear los getters y setters
|
||||||
|
class MiClaseMapeada
|
||||||
|
{
|
||||||
|
private $propiedad;
|
||||||
|
|
||||||
|
public function __get($key)
|
||||||
|
{
|
||||||
|
return $this->$key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __set($key, $value)
|
||||||
|
{
|
||||||
|
$this->$key = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$x = new MiClaseMapeada();
|
||||||
|
echo $x->propiedad; // Utilizará el método __get()
|
||||||
|
$x->propiedad = 'Algo'; // Utilizará el método __set()
|
||||||
|
|
||||||
|
// Las clases pueden ser abstractas (utilizando la palabra clave abstract) o
|
||||||
|
// implementando interfaces (utilizando la palabra clave implements).
|
||||||
|
// Una interfaz puede ser declarada con la palabra clave interface.
|
||||||
|
|
||||||
|
interface InterfazUno
|
||||||
|
{
|
||||||
|
public function hazAlgo();
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InterfazDos
|
||||||
|
{
|
||||||
|
public function hazOtraCosa();
|
||||||
|
}
|
||||||
|
|
||||||
|
// las interfaces pueden ser extendidas
|
||||||
|
interface InterfazTres extends InterfazDos
|
||||||
|
{
|
||||||
|
public function hazCualquierOtraCosa();
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class MiClaseAbstracta implements InterfazUno
|
||||||
|
{
|
||||||
|
public $x = 'hazAlgo';
|
||||||
|
}
|
||||||
|
|
||||||
|
class MiOtraClase extends MiClaseAbstracta implements InterfazDos
|
||||||
|
{
|
||||||
|
public function hazAlgo()
|
||||||
|
{
|
||||||
|
echo $x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hazOtraCosa()
|
||||||
|
{
|
||||||
|
echo 'hazOtraCosa';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Las clases pueden implementar más de una interfaz
|
||||||
|
class CualquierOtraClase implements InterfazUno, InterfazDos
|
||||||
|
{
|
||||||
|
public function hazAlgo()
|
||||||
|
{
|
||||||
|
echo 'hazAlgo';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hazOtraCosa()
|
||||||
|
{
|
||||||
|
echo 'hazOtraCosa';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Traits
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Los traits están disponibles desde PHP 5.4.0 y son declarados utilizando "trait"
|
||||||
|
|
||||||
|
trait MiTrait
|
||||||
|
{
|
||||||
|
public function miMetodoTrait()
|
||||||
|
{
|
||||||
|
print 'Tengo trait';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MiClaseTrait
|
||||||
|
{
|
||||||
|
use MiTrait;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cls = new MiClaseTrait();
|
||||||
|
$cls->miMetodoTrait(); // Imprime "Tengo trait"
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Namespaces
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Esta sección está separada porque una declaración de namespace debe
|
||||||
|
// ser la primera sentencia en un archivo. Vamos a suponer que no es el caso
|
||||||
|
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Por defecto, las clases existen en el namespace global y pueden ser llamadas
|
||||||
|
// explícitamente con una contrabarra.
|
||||||
|
|
||||||
|
$cls = new \MiClase();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Estableder el namespace para un archivo
|
||||||
|
namespace Mi\Namespace;
|
||||||
|
|
||||||
|
class MiClase
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// (de otro archivo)
|
||||||
|
$cls = new Mi\Namespace\MiClase;
|
||||||
|
|
||||||
|
// O de otro namespace.
|
||||||
|
namespace Mi\Otro\Namespace;
|
||||||
|
|
||||||
|
use Mi\Namespace\MiClase;
|
||||||
|
|
||||||
|
$cls = new MiClase();
|
||||||
|
|
||||||
|
// O se puede asignar un ales al namespace
|
||||||
|
|
||||||
|
namespace Mi\Otro\Namespace;
|
||||||
|
|
||||||
|
use Mi\Namespace as OtroNamespace;
|
||||||
|
|
||||||
|
$cls = new OtroNamespace\MiClase();
|
||||||
|
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* Late Static Binding
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
class ClasePadre {
|
||||||
|
public static function quien() {
|
||||||
|
echo "Soy una " . __CLASS__ . "\n";
|
||||||
|
}
|
||||||
|
public static function test() {
|
||||||
|
// Auto referencia a la clase en la que el método está definido
|
||||||
|
self::quien();
|
||||||
|
// Referencia estáticamente a la clase donde el método ha sido llamado
|
||||||
|
static::quien();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ClasePadre::test();
|
||||||
|
/*
|
||||||
|
Soy una ClasePadre
|
||||||
|
Soy una ClasePadre
|
||||||
|
*/
|
||||||
|
|
||||||
|
class ClaseHija extends ClasePadre {
|
||||||
|
public static function quien() {
|
||||||
|
echo "Pero soy una " . __CLASS__ . "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ClaseHija::test();
|
||||||
|
/*
|
||||||
|
Soy una ClasePadre
|
||||||
|
Pero soy una ClaseHija
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* Manejo de errores
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Una simple gestión de errores puede ser realizada con un bloque try catch
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Haz algo
|
||||||
|
} catch (Exception $e) {
|
||||||
|
// Maneja la excepción
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cuando se utilicen bloques try catch en un entorno con namespaces hay que
|
||||||
|
// usar lo siguiente
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Haz algo
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
// Maneja la excepción
|
||||||
|
}
|
||||||
|
|
||||||
|
// Excepciones personalizadas
|
||||||
|
|
||||||
|
class MiExcepcion extends Exception {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
$condicion = true;
|
||||||
|
|
||||||
|
if ($condicion) {
|
||||||
|
throw new MiExcepcion('Ha pasado algo');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (MiExcepcion $e) {
|
||||||
|
// Manejar la excepción
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Más información
|
||||||
|
|
||||||
|
Visita la [documentación oficial de PHP](http://www.php.net/manual/) para más referencias
|
||||||
|
y apoyo de la comunidad.
|
||||||
|
|
||||||
|
Si estás interesado en buenas prácticas, visita
|
||||||
|
[PHP The Right Way](http://www.phptherightway.com/).
|
||||||
|
|
||||||
|
Si vienes de un lenguaje con una buena gestión de paquetes, visita
|
||||||
|
[Composer](http://getcomposer.org/).
|
||||||
|
|
||||||
|
Para estándares comunes, visita el PHP Framework Interoperability Group
|
||||||
|
[PSR standards](https://github.com/php-fig/fig-standards).
|
@ -97,7 +97,7 @@ not False # => True
|
|||||||
None # => None
|
None # => None
|
||||||
|
|
||||||
# No uses el símbolo de igualdad `==` para comparar objetos con None
|
# No uses el símbolo de igualdad `==` para comparar objetos con None
|
||||||
# Usa `is` en lugar de
|
# Usa `is` en su lugar
|
||||||
"etc" is None #=> False
|
"etc" is None #=> False
|
||||||
None is None #=> True
|
None is None #=> True
|
||||||
|
|
||||||
@ -383,7 +383,7 @@ def keyword_args(**kwargs):
|
|||||||
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
|
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
|
||||||
|
|
||||||
|
|
||||||
# You can do both at once, if you like# Puedes hacer ambas a la vez si quieres
|
# Puedes hacer ambas a la vez si quieres
|
||||||
def todos_los_argumentos(*args, **kwargs):
|
def todos_los_argumentos(*args, **kwargs):
|
||||||
print args
|
print args
|
||||||
print kwargs
|
print kwargs
|
||||||
@ -478,7 +478,7 @@ Humano.roncar() #=> "*roncar*"
|
|||||||
|
|
||||||
# Puedes importar módulos
|
# Puedes importar módulos
|
||||||
import math
|
import math
|
||||||
print(math.sqrt(16)) #=> 4
|
print(math.sqrt(16)) #=> 4.0
|
||||||
|
|
||||||
# Puedes obtener funciones específicas desde un módulo
|
# Puedes obtener funciones específicas desde un módulo
|
||||||
from math import ceil, floor
|
from math import ceil, floor
|
||||||
@ -511,7 +511,7 @@ def duplicar_numeros(iterable):
|
|||||||
for i in iterable:
|
for i in iterable:
|
||||||
yield i + i
|
yield i + i
|
||||||
|
|
||||||
# Un generador cera valores sobre la marcha.
|
# Un generador crea valores sobre la marcha.
|
||||||
# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
|
# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
|
||||||
# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
|
# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
|
||||||
# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
|
# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
|
||||||
|
@ -29,7 +29,7 @@ Nadie los usa.
|
|||||||
Tu tampoco deberías
|
Tu tampoco deberías
|
||||||
=end
|
=end
|
||||||
|
|
||||||
# Lo primero y principal: Todo es un objeto
|
# En primer lugar: Todo es un objeto
|
||||||
|
|
||||||
# Los números son objetos
|
# Los números son objetos
|
||||||
|
|
||||||
@ -128,7 +128,7 @@ ruta = '/mal/nombre/'
|
|||||||
|
|
||||||
# Los símbolos (son objetos)
|
# Los símbolos (son objetos)
|
||||||
# Los símbolos son inmutables, constantes reusables representadas internamente por un
|
# Los símbolos son inmutables, constantes reusables representadas internamente por un
|
||||||
# valor entero. Son usalmente usados en vez de strings para expresar eficientemente
|
# valor entero. Son normalmente usados en vez de strings para expresar eficientemente
|
||||||
# valores específicos y significativos
|
# valores específicos y significativos
|
||||||
|
|
||||||
:pendiente.class #=> Symbol
|
:pendiente.class #=> Symbol
|
||||||
@ -156,7 +156,7 @@ arreglo[0] #=> 1
|
|||||||
arreglo.first #=> 1
|
arreglo.first #=> 1
|
||||||
arreglo[12] #=> nil
|
arreglo[12] #=> nil
|
||||||
|
|
||||||
# Tal como la aritmética, el acceso como variable[índice]
|
# Al igual que en aritmética, el acceso como variable[índice]
|
||||||
# es sólo azúcar sintáctica
|
# es sólo azúcar sintáctica
|
||||||
# para llamar el método [] de un objeto
|
# para llamar el método [] de un objeto
|
||||||
arreglo.[] 0 #=> 1
|
arreglo.[] 0 #=> 1
|
||||||
|
596
es-es/swift-es.html.markdown
Normal file
596
es-es/swift-es.html.markdown
Normal file
@ -0,0 +1,596 @@
|
|||||||
|
---
|
||||||
|
language: swift
|
||||||
|
contributors:
|
||||||
|
- ["Grant Timmerman", "http://github.com/grant"]
|
||||||
|
- ["Christopher Bess", "http://github.com/cbess"]
|
||||||
|
- ["Joey Huang", "http://github.com/kamidox"]
|
||||||
|
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
||||||
|
translators:
|
||||||
|
- ["David Hsieh", "http://github.com/deivuh"]
|
||||||
|
lang: es-es
|
||||||
|
filename: learnswift-es.swift
|
||||||
|
---
|
||||||
|
|
||||||
|
Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
|
||||||
|
por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
|
||||||
|
el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia
|
||||||
|
de desarrolladores de Apple.
|
||||||
|
|
||||||
|
Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), el cual tiene un completo tutorial de Swift.
|
||||||
|
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// Importar un módulo
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Básicos
|
||||||
|
//
|
||||||
|
|
||||||
|
// XCode soporta referencias para anotar tu código y agregarlos a lista de la
|
||||||
|
// barra de saltos.
|
||||||
|
// MARK: Marca de sección
|
||||||
|
// TODO: Hacer algo pronto
|
||||||
|
// FIXME: Arreglar este código
|
||||||
|
|
||||||
|
// En Swift 2, println y print fueron combinados en un solo método print.
|
||||||
|
// Print añade una nueva línea automáticamente.
|
||||||
|
print("Hola, mundo") // println ahora es print
|
||||||
|
print("Hola, mundo", appendNewLine: false) // print sin agregar nueva línea
|
||||||
|
|
||||||
|
// Valores de variables (var) pueden cambiar después de ser asignados
|
||||||
|
// Valores de constrantes (let) no pueden cambiarse después de ser asignados
|
||||||
|
|
||||||
|
var myVariable = 42
|
||||||
|
let øπΩ = "value" // nombres de variable unicode
|
||||||
|
let π = 3.1415926
|
||||||
|
let convenience = "keyword" // nombre de variable contextual
|
||||||
|
// Las declaraciones pueden ser separadas por punto y coma (;)
|
||||||
|
let weak = "keyword"; let override = "another keyword"
|
||||||
|
// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de
|
||||||
|
// variable
|
||||||
|
let `class` = "keyword"
|
||||||
|
let explicitDouble: Double = 70
|
||||||
|
let intValue = 0007 // 7
|
||||||
|
let largeIntValue = 77_000 // 77000
|
||||||
|
let label = "some text " + String(myVariable) // Conversión (casting)
|
||||||
|
let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
|
||||||
|
|
||||||
|
// Valores específicos de la compilación (build)
|
||||||
|
// utiliza la configuración -D
|
||||||
|
#if false
|
||||||
|
print("No impreso")
|
||||||
|
let buildValue = 3
|
||||||
|
#else
|
||||||
|
let buildValue = 7
|
||||||
|
#endif
|
||||||
|
print("Build value: \(buildValue)") // Build value: 7
|
||||||
|
|
||||||
|
/*
|
||||||
|
Las opcionales son un aspecto del lenguaje Swift que permite el
|
||||||
|
almacenamiento de un valor `Some` (algo) o `None` (nada).
|
||||||
|
|
||||||
|
Debido a que Swift requiere que cada propiedad tenga un valor,
|
||||||
|
hasta un valor 'nil' debe de ser explicitamente almacenado como un
|
||||||
|
valor opcional.
|
||||||
|
|
||||||
|
Optional<T> es un enum.
|
||||||
|
*/
|
||||||
|
var someOptionalString: String? = "opcional" // Puede ser nil
|
||||||
|
// Al igual que lo anterior, pero ? es un operador postfix (sufijo)
|
||||||
|
var someOptionalString2: Optional<String> = "opcional"
|
||||||
|
|
||||||
|
if someOptionalString != nil {
|
||||||
|
// No soy nil
|
||||||
|
if someOptionalString!.hasPrefix("opt") {
|
||||||
|
print("Tiene el prefijo")
|
||||||
|
}
|
||||||
|
|
||||||
|
let empty = someOptionalString?.isEmpty
|
||||||
|
}
|
||||||
|
someOptionalString = nil
|
||||||
|
|
||||||
|
// Opcional implícitamente desenvuelto
|
||||||
|
var unwrappedString: String! = "Un valor esperado."
|
||||||
|
// Al igual que lo anterior, pero ! es un operador postfix (sufijo)
|
||||||
|
var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Un valor esperado."
|
||||||
|
|
||||||
|
if let someOptionalStringConstant = someOptionalString {
|
||||||
|
// tiene valor `Some` (algo), no nil
|
||||||
|
if !someOptionalStringConstant.hasPrefix("ok") {
|
||||||
|
// No tiene el prefijo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Swift tiene soporte de almacenamiento para cualquier tipo de valor.
|
||||||
|
// AnyObject == id
|
||||||
|
// A diferencia de Objective-C `id`, AnyObject funciona con cualquier
|
||||||
|
// valor (Class, Int, struct, etc)
|
||||||
|
var anyObjectVar: AnyObject = 7
|
||||||
|
anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible."
|
||||||
|
|
||||||
|
/*
|
||||||
|
Comentar aquí
|
||||||
|
|
||||||
|
/*
|
||||||
|
Comentarios anidados también son soportados
|
||||||
|
*/
|
||||||
|
*/
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Colecciones
|
||||||
|
//
|
||||||
|
|
||||||
|
/*
|
||||||
|
Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras).
|
||||||
|
Así que `let` y `var` también indican si son mudables (var) o
|
||||||
|
inmutables (let) durante la declaración de sus tipos.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Array (arreglo)
|
||||||
|
var shoppingList = ["catfish", "water", "lemons"]
|
||||||
|
shoppingList[1] = "bottle of water"
|
||||||
|
let emptyArray = [String]() // let == inmutable
|
||||||
|
let emptyArray2 = Array<String>() // igual que lo anterior
|
||||||
|
var emptyMutableArray = [String]() // var == mudable
|
||||||
|
|
||||||
|
|
||||||
|
// Dictionary (diccionario)
|
||||||
|
var occupations = [
|
||||||
|
"Malcolm": "Captain",
|
||||||
|
"kaylee": "Mechanic"
|
||||||
|
]
|
||||||
|
occupations["Jayne"] = "Public Relations"
|
||||||
|
let emptyDictionary = [String: Float]() // let == inmutable
|
||||||
|
let emptyDictionary2 = Dictionary<String, Float>() // igual que lo anterior
|
||||||
|
var emptyMutableDictionary = [String: Float]() // var == mudable
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Flujo de control
|
||||||
|
//
|
||||||
|
|
||||||
|
// Ciclo for (array)
|
||||||
|
let myArray = [1, 1, 2, 3, 5]
|
||||||
|
for value in myArray {
|
||||||
|
if value == 1 {
|
||||||
|
print("Uno!")
|
||||||
|
} else {
|
||||||
|
print("No es uno!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ciclo for (dictionary)
|
||||||
|
var dict = ["uno": 1, "dos": 2]
|
||||||
|
for (key, value) in dict {
|
||||||
|
print("\(key): \(value)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ciclo for (range)
|
||||||
|
for i in -1...shoppingList.count {
|
||||||
|
print(i)
|
||||||
|
}
|
||||||
|
shoppingList[1...2] = ["steak", "peacons"]
|
||||||
|
// Utilizar ..< para excluir el último valor
|
||||||
|
|
||||||
|
// Ciclo while
|
||||||
|
var i = 1
|
||||||
|
while i < 1000 {
|
||||||
|
i *= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ciclo do-while
|
||||||
|
do {
|
||||||
|
print("Hola")
|
||||||
|
} while 1 == 2
|
||||||
|
|
||||||
|
// Switch
|
||||||
|
// Muy potente, se puede pensar como declaraciones `if` con _azúcar sintáctico_
|
||||||
|
// Soportan String, instancias de objetos, y primitivos (Int, Double, etc)
|
||||||
|
let vegetable = "red pepper"
|
||||||
|
switch vegetable {
|
||||||
|
case "celery":
|
||||||
|
let vegetableComment = "Add some raisins and make ants on a log."
|
||||||
|
case "cucumber", "watercress":
|
||||||
|
let vegetableComment = "That would make a good tea sandwich."
|
||||||
|
case let localScopeValue where localScopeValue.hasSuffix("pepper"):
|
||||||
|
let vegetableComment = "Is it a spicy \(localScopeValue)?"
|
||||||
|
default: // obligatorio (se debe cumplir con todos los posibles valores de entrada)
|
||||||
|
let vegetableComment = "Everything tastes good in soup."
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Funciones
|
||||||
|
//
|
||||||
|
|
||||||
|
// Funciones son un tipo de primera-clase, quiere decir que pueden ser anidados
|
||||||
|
// en funciones y pueden ser pasados como parámetros
|
||||||
|
|
||||||
|
// Función en documentación de cabeceras Swift (formato reStructedText)
|
||||||
|
|
||||||
|
/**
|
||||||
|
Una operación de saludo
|
||||||
|
|
||||||
|
- Una viñeta en la documentación
|
||||||
|
- Otra viñeta en la documentación
|
||||||
|
|
||||||
|
:param: name Un nombre
|
||||||
|
:param: day Un día
|
||||||
|
:returns: Un string que contiene el valor de name y day
|
||||||
|
*/
|
||||||
|
func greet(name: String, day: String) -> String {
|
||||||
|
return "Hola \(name), hoy es \(day)."
|
||||||
|
}
|
||||||
|
greet("Bob", "Martes")
|
||||||
|
|
||||||
|
// Similar a lo anterior, a excepción del compartamiento de los parámetros
|
||||||
|
// de la función
|
||||||
|
func greet2(requiredName: String, externalParamName localParamName: String) -> String {
|
||||||
|
return "Hola \(requiredName), hoy es el día \(localParamName)"
|
||||||
|
}
|
||||||
|
greet2(requiredName:"John", externalParamName: "Domingo")
|
||||||
|
|
||||||
|
// Función que devuelve múltiples valores en una tupla
|
||||||
|
func getGasPrices() -> (Double, Double, Double) {
|
||||||
|
return (3.59, 3.69, 3.79)
|
||||||
|
}
|
||||||
|
let pricesTuple = getGasPrices()
|
||||||
|
let price = pricesTuple.2 // 3.79
|
||||||
|
// Ignorar tupla (u otros) valores utilizando _ (guión bajo)
|
||||||
|
let (_, price1, _) = pricesTuple // price1 == 3.69
|
||||||
|
print(price1 == pricesTuple.1) // true
|
||||||
|
print("Gas price: \(price)")
|
||||||
|
|
||||||
|
// Cantidad variable de argumentos
|
||||||
|
func setup(numbers: Int...) {
|
||||||
|
// Es un arreglo
|
||||||
|
let number = numbers[0]
|
||||||
|
let argCount = numbers.count
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pasando y devolviendo funciones
|
||||||
|
func makeIncrementer() -> (Int -> Int) {
|
||||||
|
func addOne(number: Int) -> Int {
|
||||||
|
return 1 + number
|
||||||
|
}
|
||||||
|
return addOne
|
||||||
|
}
|
||||||
|
var increment = makeIncrementer()
|
||||||
|
increment(7)
|
||||||
|
|
||||||
|
// Pasando como referencia
|
||||||
|
func swapTwoInts(inout a: Int, inout b: Int) {
|
||||||
|
let tempA = a
|
||||||
|
a = b
|
||||||
|
b = tempA
|
||||||
|
}
|
||||||
|
var someIntA = 7
|
||||||
|
var someIntB = 3
|
||||||
|
swapTwoInts(&someIntA, &someIntB)
|
||||||
|
print(someIntB) // 7
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Closures (Clausuras)
|
||||||
|
//
|
||||||
|
var numbers = [1, 2, 6]
|
||||||
|
|
||||||
|
// Las funciones son un caso especial de closure ({})
|
||||||
|
|
||||||
|
// Ejemplo de closure.
|
||||||
|
// `->` Separa los argumentos del tipo de retorno
|
||||||
|
// `in` Separa la cabecera del cuerpo del closure
|
||||||
|
numbers.map({
|
||||||
|
(number: Int) -> Int in
|
||||||
|
let result = 3 * number
|
||||||
|
return result
|
||||||
|
})
|
||||||
|
|
||||||
|
// Cuando se conoce el tipo, como en lo anterior, se puede hacer esto
|
||||||
|
numbers = numbers.map({ number in 3 * number })
|
||||||
|
// o esto
|
||||||
|
//numbers = numbers.map({ $0 * 3 })
|
||||||
|
|
||||||
|
print(numbers) // [3, 6, 18]
|
||||||
|
|
||||||
|
// Closure restante
|
||||||
|
numbers = sorted(numbers) { $0 > $1 }
|
||||||
|
|
||||||
|
print(numbers) // [18, 6, 3]
|
||||||
|
|
||||||
|
// Bastante corto, debido a que el operador < infiere los tipos
|
||||||
|
|
||||||
|
numbers = sorted(numbers, < )
|
||||||
|
|
||||||
|
print(numbers) // [3, 6, 18]
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Estructuras
|
||||||
|
//
|
||||||
|
|
||||||
|
// Las estructuras y las clases tienen capacidades similares
|
||||||
|
struct NamesTable {
|
||||||
|
let names = [String]()
|
||||||
|
|
||||||
|
// Subscript personalizado
|
||||||
|
subscript(index: Int) -> String {
|
||||||
|
return names[index]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Las estructuras tienen un inicializador designado autogenerado (implícitamente)
|
||||||
|
let namesTable = NamesTable(names: ["Me", "Them"])
|
||||||
|
let name = namesTable[1]
|
||||||
|
print("Name is \(name)") // Name is Them
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Clases
|
||||||
|
//
|
||||||
|
|
||||||
|
// Las clases, las estructuras y sus miembros tienen tres niveles de control de acceso
|
||||||
|
// Éstos son: internal (predeterminado), public, private
|
||||||
|
|
||||||
|
public class Shape {
|
||||||
|
public func getArea() -> Int {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Todos los métodos y las propiedades de una clase son public (públicas)
|
||||||
|
// Si solo necesitas almacenar datos en un objecto estructurado,
|
||||||
|
// debes de utilizar `struct`
|
||||||
|
|
||||||
|
internal class Rect: Shape {
|
||||||
|
var sideLength: Int = 1
|
||||||
|
|
||||||
|
// Getter y setter personalizado
|
||||||
|
private var perimeter: Int {
|
||||||
|
get {
|
||||||
|
return 4 * sideLength
|
||||||
|
}
|
||||||
|
set {
|
||||||
|
// `newValue` es una variable implícita disponible para los setters
|
||||||
|
sideLength = newValue / 4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lazily loading (inicialización bajo demanda) a una propiedad
|
||||||
|
// subShape queda como nil (sin inicializar) hasta que getter es llamado
|
||||||
|
lazy var subShape = Rect(sideLength: 4)
|
||||||
|
|
||||||
|
// Si no necesitas un getter y setter personalizado
|
||||||
|
// pero aún quieres ejecutar código antes y después de hacer get o set
|
||||||
|
// a una propiedad, puedes utilizar `willSet` y `didSet`
|
||||||
|
var identifier: String = "defaultID" {
|
||||||
|
// El argumento `willSet` será el nombre de variable para el nuevo valor
|
||||||
|
willSet(someIdentifier) {
|
||||||
|
print(someIdentifier)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
init(sideLength: Int) {
|
||||||
|
self.sideLength = sideLength
|
||||||
|
// Siempre poner super.init de último al momento de inicializar propiedades
|
||||||
|
// personalizadas
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
func shrink() {
|
||||||
|
if sideLength > 0 {
|
||||||
|
--sideLength
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func getArea() -> Int {
|
||||||
|
return sideLength * sideLength
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Una clase simple `Square` que extiende de `Rect`
|
||||||
|
class Square: Rect {
|
||||||
|
convenience init() {
|
||||||
|
self.init(sideLength: 5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var mySquare = Square()
|
||||||
|
print(mySquare.getArea()) // 25
|
||||||
|
mySquare.shrink()
|
||||||
|
print(mySquare.sideLength) // 4
|
||||||
|
|
||||||
|
// Conversión de tipo de instancia
|
||||||
|
let aShape = mySquare as Shape
|
||||||
|
|
||||||
|
// Comparar instancias, no es igual a == que compara objetos (equal to)
|
||||||
|
if mySquare === mySquare {
|
||||||
|
print("Yep, it's mySquare")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inicialización (init) opcional
|
||||||
|
class Circle: Shape {
|
||||||
|
var radius: Int
|
||||||
|
override func getArea() -> Int {
|
||||||
|
return 3 * radius * radius
|
||||||
|
}
|
||||||
|
|
||||||
|
// Un signo de interrogación como sufijo después de `init` es un init opcional
|
||||||
|
// que puede devolver nil
|
||||||
|
init?(radius: Int) {
|
||||||
|
self.radius = radius
|
||||||
|
super.init()
|
||||||
|
|
||||||
|
if radius <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var myCircle = Circle(radius: 1)
|
||||||
|
print(myCircle?.getArea()) // Optional(3)
|
||||||
|
print(myCircle!.getArea()) // 3
|
||||||
|
var myEmptyCircle = Circle(radius: -1)
|
||||||
|
print(myEmptyCircle?.getArea()) // "nil"
|
||||||
|
if let circle = myEmptyCircle {
|
||||||
|
// no será ejecutado debido a que myEmptyCircle es nil
|
||||||
|
print("circle is not nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Enums
|
||||||
|
//
|
||||||
|
|
||||||
|
|
||||||
|
// Los enums pueden ser opcionalmente de un tipo específico o de su propio tipo
|
||||||
|
// Al igual que las clases, pueden contener métodos
|
||||||
|
|
||||||
|
enum Suit {
|
||||||
|
case Spades, Hearts, Diamonds, Clubs
|
||||||
|
func getIcon() -> String {
|
||||||
|
switch self {
|
||||||
|
case .Spades: return "♤"
|
||||||
|
case .Hearts: return "♡"
|
||||||
|
case .Diamonds: return "♢"
|
||||||
|
case .Clubs: return "♧"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Los valores de enum permite la sintaxis corta, sin necesidad de poner
|
||||||
|
// el tipo del enum cuando la variable es declarada de manera explícita
|
||||||
|
var suitValue: Suit = .Hearts
|
||||||
|
|
||||||
|
// Enums de tipo no-entero requiere asignaciones de valores crudas directas
|
||||||
|
enum BookName: String {
|
||||||
|
case John = "John"
|
||||||
|
case Luke = "Luke"
|
||||||
|
}
|
||||||
|
print("Name: \(BookName.John.rawValue)")
|
||||||
|
|
||||||
|
// Enum con valores asociados
|
||||||
|
enum Furniture {
|
||||||
|
// Asociación con Int
|
||||||
|
case Desk(height: Int)
|
||||||
|
// Asociación con String e Int
|
||||||
|
case Chair(String, Int)
|
||||||
|
|
||||||
|
func description() -> String {
|
||||||
|
switch self {
|
||||||
|
case .Desk(let height):
|
||||||
|
return "Desk with \(height) cm"
|
||||||
|
case .Chair(let brand, let height):
|
||||||
|
return "Chair of \(brand) with \(height) cm"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var desk: Furniture = .Desk(height: 80)
|
||||||
|
print(desk.description()) // "Desk with 80 cm"
|
||||||
|
var chair = Furniture.Chair("Foo", 40)
|
||||||
|
print(chair.description()) // "Chair of Foo with 40 cm"
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Protocolos
|
||||||
|
//
|
||||||
|
|
||||||
|
// `protocol` puede requerir que los tipos tengan propiedades
|
||||||
|
// de instancia específicas, métodos de instancia, métodos de tipo,
|
||||||
|
// operadores, y subscripts
|
||||||
|
|
||||||
|
|
||||||
|
protocol ShapeGenerator {
|
||||||
|
var enabled: Bool { get set }
|
||||||
|
func buildShape() -> Shape
|
||||||
|
}
|
||||||
|
|
||||||
|
// Protocolos declarados con @objc permiten funciones opcionales,
|
||||||
|
// que te permite evaluar conformidad
|
||||||
|
@objc protocol TransformShape {
|
||||||
|
optional func reshaped()
|
||||||
|
optional func canReshape() -> Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyShape: Rect {
|
||||||
|
var delegate: TransformShape?
|
||||||
|
|
||||||
|
func grow() {
|
||||||
|
sideLength += 2
|
||||||
|
|
||||||
|
// Pon un signo de interrogación después de la propiedad opcional,
|
||||||
|
// método, o subscript para ignorar un valor nil y devolver nil
|
||||||
|
// en lugar de tirar un error de tiempo de ejecución
|
||||||
|
// ("optional chaining")
|
||||||
|
if let allow = self.delegate?.canReshape?() {
|
||||||
|
// test for delegate then for method
|
||||||
|
self.delegate?.reshaped?()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// MARK: Otros
|
||||||
|
//
|
||||||
|
|
||||||
|
// `extension`: Agrega funcionalidades a tipos existentes
|
||||||
|
|
||||||
|
// Square ahora se "conforma" al protocolo `Printable`
|
||||||
|
extension Square: Printable {
|
||||||
|
var description: String {
|
||||||
|
return "Area: \(self.getArea()) - ID: \(self.identifier)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
print("Square: \(mySquare)")
|
||||||
|
|
||||||
|
// También puedes hacer extend a tipos prefabricados (built-in)
|
||||||
|
extension Int {
|
||||||
|
var customProperty: String {
|
||||||
|
return "This is \(self)"
|
||||||
|
}
|
||||||
|
|
||||||
|
func multiplyBy(num: Int) -> Int {
|
||||||
|
return num * self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
print(7.customProperty) // "This is 7"
|
||||||
|
print(14.multiplyBy(3)) // 42
|
||||||
|
|
||||||
|
// Generics: Similar Java y C#. Utiliza la palabra clave `where` para
|
||||||
|
// especificar los requerimientos de los genéricos.
|
||||||
|
|
||||||
|
func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
|
||||||
|
for (index, value) in enumerate(array) {
|
||||||
|
if value == valueToFind {
|
||||||
|
return index
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
let foundAtIndex = findIndex([1, 2, 3, 4], 3)
|
||||||
|
print(foundAtIndex == 2) // true
|
||||||
|
|
||||||
|
// Operadores:
|
||||||
|
// Operadores personalizados puede empezar con los siguientes caracteres:
|
||||||
|
// / = - + * % < > ! & | ^ . ~
|
||||||
|
// o
|
||||||
|
// Caracteres unicode: math, symbol, arrow, dingbat, y line/box.
|
||||||
|
prefix operator !!! {}
|
||||||
|
|
||||||
|
// Un operador prefix que triplica la longitud del lado cuando es utilizado
|
||||||
|
prefix func !!! (inout shape: Square) -> Square {
|
||||||
|
shape.sideLength *= 3
|
||||||
|
return shape
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valor actual
|
||||||
|
print(mySquare.sideLength) // 4
|
||||||
|
|
||||||
|
// Cambiar la longitud del lado utilizando el operador !!!,
|
||||||
|
// incrementa el tamaño por 3
|
||||||
|
!!!mySquare
|
||||||
|
print(mySquare.sideLength) // 12
|
||||||
|
```
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Mohammad Valipour", "https://github.com/mvalipour"]
|
- ["Mohammad Valipour", "https://github.com/mvalipour"]
|
||||||
lang: fa-ir
|
lang: fa-ir
|
182
factor.html.markdown
Normal file
182
factor.html.markdown
Normal file
@ -0,0 +1,182 @@
|
|||||||
|
---
|
||||||
|
language: factor
|
||||||
|
contributors:
|
||||||
|
- ["hyphz", "http://github.com/hyphz/"]
|
||||||
|
filename: learnfactor.factor
|
||||||
|
---
|
||||||
|
|
||||||
|
Factor is a modern stack-based language, based on Forth, created by Slava Pestov.
|
||||||
|
|
||||||
|
Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing.
|
||||||
|
|
||||||
|
```
|
||||||
|
! This is a comment
|
||||||
|
|
||||||
|
! Like Forth, all programming is done by manipulating the stack.
|
||||||
|
! Stating a literal value pushes it onto the stack.
|
||||||
|
5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode
|
||||||
|
|
||||||
|
! Those numbers get added to the stack, from left to right.
|
||||||
|
! .s prints out the stack non-destructively.
|
||||||
|
.s ! 5 2 3 56 76 23 65
|
||||||
|
|
||||||
|
! Arithmetic works by manipulating data on the stack.
|
||||||
|
5 4 + ! No output
|
||||||
|
|
||||||
|
! `.` pops the top result from the stack and prints it.
|
||||||
|
. ! 9
|
||||||
|
|
||||||
|
! More examples of arithmetic:
|
||||||
|
6 7 * . ! 42
|
||||||
|
1360 23 - . ! 1337
|
||||||
|
12 12 / . ! 1
|
||||||
|
13 2 mod . ! 1
|
||||||
|
|
||||||
|
99 neg . ! -99
|
||||||
|
-99 abs . ! 99
|
||||||
|
52 23 max . ! 52
|
||||||
|
52 23 min . ! 23
|
||||||
|
|
||||||
|
! A number of words are provided to manipulate the stack, collectively known as shuffle words.
|
||||||
|
|
||||||
|
3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3
|
||||||
|
2 5 swap / ! swap the top with the second element: 5 / 2
|
||||||
|
4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2
|
||||||
|
1 2 3 nip .s ! remove the second item (similar to drop): 1 3
|
||||||
|
1 2 clear .s ! wipe out the entire stack
|
||||||
|
1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3
|
||||||
|
1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3
|
||||||
|
|
||||||
|
! Creating Words
|
||||||
|
! The `:` word sets Factor into compile mode until it sees the `;` word.
|
||||||
|
: square ( n -- n ) dup * ; ! No output
|
||||||
|
5 square . ! 25
|
||||||
|
|
||||||
|
! We can view what a word does too.
|
||||||
|
! \ suppresses evaluation of a word and pushes its identifier on the stack instead.
|
||||||
|
\ square see ! : square ( n -- n ) dup * ;
|
||||||
|
|
||||||
|
! After the name of the word to create, the declaration between brackets gives the stack effect.
|
||||||
|
! We can use whatever names we like inside the declaration:
|
||||||
|
: weirdsquare ( camel -- llama ) dup * ;
|
||||||
|
|
||||||
|
! Provided their count matches the word's stack effect:
|
||||||
|
: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong
|
||||||
|
: doubledup ( a -- a a a ) dup dup ; ! Ok
|
||||||
|
: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok
|
||||||
|
|
||||||
|
! Where Factor differs from Forth is in the use of quotations.
|
||||||
|
! A quotation is a block of code that is pushed on the stack as a value.
|
||||||
|
! [ starts quotation mode; ] ends it.
|
||||||
|
[ 2 + ] ! Quotation that adds 2 is left on the stack
|
||||||
|
4 swap call . ! 6
|
||||||
|
|
||||||
|
! And thus, higher order words. TONS of higher order words.
|
||||||
|
2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3
|
||||||
|
3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4
|
||||||
|
1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4
|
||||||
|
4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 )
|
||||||
|
1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values
|
||||||
|
2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack
|
||||||
|
|
||||||
|
! Conditionals
|
||||||
|
! Any value is true except the built-in value f.
|
||||||
|
! A built-in value t does exist, but its use isn't essential.
|
||||||
|
! Conditionals are higher order words as with the combinators above.
|
||||||
|
|
||||||
|
5 [ "Five is true" . ] when ! Five is true
|
||||||
|
0 [ "Zero is true" . ] when ! Zero is true
|
||||||
|
f [ "F is true" . ] when ! No output
|
||||||
|
f [ "F is false" . ] unless ! F is false
|
||||||
|
2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true
|
||||||
|
|
||||||
|
! By default the conditionals consume the value under test, but starred variants
|
||||||
|
! leave it alone if it's true:
|
||||||
|
|
||||||
|
5 [ . ] when* ! 5
|
||||||
|
f [ . ] when* ! No output, empty stack, f is consumed because it's false
|
||||||
|
|
||||||
|
|
||||||
|
! Loops
|
||||||
|
! You've guessed it.. these are higher order words too.
|
||||||
|
|
||||||
|
5 [ . ] each-integer ! 0 1 2 3 4
|
||||||
|
4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8
|
||||||
|
5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello
|
||||||
|
|
||||||
|
! Here's a list:
|
||||||
|
{ 2 4 6 8 } ! Goes on the stack as one item
|
||||||
|
|
||||||
|
! Loop through the list:
|
||||||
|
{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9
|
||||||
|
{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack
|
||||||
|
|
||||||
|
! Loop reducing or building lists:
|
||||||
|
{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 }
|
||||||
|
{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8)
|
||||||
|
{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20
|
||||||
|
1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 }
|
||||||
|
1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 }
|
||||||
|
|
||||||
|
! If all else fails, a general purpose while loop:
|
||||||
|
1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times
|
||||||
|
! Yes, it's hard to read
|
||||||
|
! That's what all those variant loops are for
|
||||||
|
|
||||||
|
! Variables
|
||||||
|
! Usually Factor programs are expected to keep all data on the stack.
|
||||||
|
! Using named variables makes refactoring harder (and it's called Factor for a reason)
|
||||||
|
! Global variables, if you must:
|
||||||
|
|
||||||
|
SYMBOL: name ! Creates name as an identifying word
|
||||||
|
"Bob" name set-global ! No output
|
||||||
|
name get-global . ! "Bob"
|
||||||
|
|
||||||
|
! Named local variables are considered an extension but are available
|
||||||
|
! In a quotation..
|
||||||
|
[| m n ! Quotation captures top two stack values into m and n
|
||||||
|
| m n + ] ! Read them
|
||||||
|
|
||||||
|
! Or in a word..
|
||||||
|
:: lword ( -- ) ! Note double colon to invoke lexical variable extension
|
||||||
|
2 :> c ! Declares immutable variable c to hold 2
|
||||||
|
c . ; ! Print it out
|
||||||
|
|
||||||
|
! In a word declared this way, the input side of the stack declaration
|
||||||
|
! becomes meaningful and gives the variable names stack values are captured into
|
||||||
|
:: double ( a -- result ) a 2 * ;
|
||||||
|
|
||||||
|
! Variables are declared mutable by ending their name with a shriek
|
||||||
|
:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a
|
||||||
|
a ! Push a
|
||||||
|
a 2 * a! ! Multiply a by 2 and store result back in a
|
||||||
|
a ; ! Push new value of a
|
||||||
|
5 mword2 ! Stack: 5 10
|
||||||
|
|
||||||
|
! Lists and Sequences
|
||||||
|
! We saw above how to push a list onto the stack
|
||||||
|
|
||||||
|
0 { 1 2 3 4 } nth ! Access a particular member of a list: 1
|
||||||
|
10 { 1 2 3 4 } nth ! Error: sequence index out of bounds
|
||||||
|
1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2
|
||||||
|
10 { 1 2 3 4 } ?nth ! No error if out of bounds: f
|
||||||
|
|
||||||
|
{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" }
|
||||||
|
{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" }
|
||||||
|
"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" }
|
||||||
|
"Concat" "enate" append ! "Concatenate" - strings are sequences too
|
||||||
|
"Concatenate" "Reverse " prepend ! "Reverse Concatenate"
|
||||||
|
{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs"
|
||||||
|
{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators"
|
||||||
|
|
||||||
|
! And if you want to get meta, quotations are sequences and can be dismantled..
|
||||||
|
0 [ 2 + ] nth ! 2
|
||||||
|
1 [ 2 + ] nth ! +
|
||||||
|
[ 2 + ] \ - suffix ! Quotation [ 2 + - ]
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
##Ready For More?
|
||||||
|
|
||||||
|
* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html)
|
441
fi-fi/go-fi.html.markdown
Normal file
441
fi-fi/go-fi.html.markdown
Normal file
@ -0,0 +1,441 @@
|
|||||||
|
---
|
||||||
|
name: Go
|
||||||
|
category: language
|
||||||
|
language: Go
|
||||||
|
filename: learngo-fi.go
|
||||||
|
contributors:
|
||||||
|
- ["Sonia Keys", "https://github.com/soniakeys"]
|
||||||
|
- ["Christopher Bess", "https://github.com/cbess"]
|
||||||
|
- ["Jesse Johnson", "https://github.com/holocronweaver"]
|
||||||
|
- ["Quint Guvernator", "https://github.com/qguv"]
|
||||||
|
- ["Jose Donizetti", "https://github.com/josedonizetti"]
|
||||||
|
- ["Alexej Friesen", "https://github.com/heyalexej"]
|
||||||
|
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||||
|
translators:
|
||||||
|
- ["Timo Virkkunen", "https://github.com/ComSecNinja"]
|
||||||
|
lang: fi-fi
|
||||||
|
---
|
||||||
|
|
||||||
|
Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi,
|
||||||
|
mutta se on uusin nopein tapa ratkaista oikean maailman ongelmia.
|
||||||
|
|
||||||
|
Sillä on staattisesti tyypitetyistä imperatiivisista kielistä tuttuja
|
||||||
|
konsepteja. Se kääntyy ja suorittuu nopeasti, lisää helposti käsitettävän
|
||||||
|
samanaikaisten komentojen suorittamisen nykyaikaisten moniytimisten
|
||||||
|
prosessoreiden hyödyntämiseksi ja antaa käyttäjälle ominaisuuksia suurten
|
||||||
|
projektien käsittelemiseksi.
|
||||||
|
|
||||||
|
Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön.
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Yhden rivin kommentti
|
||||||
|
/* Useamman
|
||||||
|
rivin kommentti */
|
||||||
|
|
||||||
|
// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto.
|
||||||
|
// Main on erityinen nimi joka ilmoittaa
|
||||||
|
// suoritettavan tiedoston kirjaston sijasta.
|
||||||
|
package main
|
||||||
|
|
||||||
|
// Import -lauseke ilmoittaa tässä tiedostossa käytetyt kirjastot.
|
||||||
|
import (
|
||||||
|
"fmt" // Paketti Go:n oletuskirjastosta.
|
||||||
|
"io/ioutil" // Implementoi hyödyllisiä I/O -funktioita.
|
||||||
|
m "math" // Matematiikkakirjasto jolla on paikallinen nimi m.
|
||||||
|
"net/http" // Kyllä, web-palvelin!
|
||||||
|
"strconv" // Kirjainjonojen muuntajia.
|
||||||
|
)
|
||||||
|
|
||||||
|
// Funktion määrittelijä. Main on erityinen: se on ohjelman suorittamisen
|
||||||
|
// aloittamisen alkupiste. Rakasta tai vihaa sitä, Go käyttää aaltosulkeita.
|
||||||
|
func main() {
|
||||||
|
// Println tulostaa rivin stdoutiin.
|
||||||
|
// Se tulee paketin fmt mukana, joten paketin nimi on mainittava.
|
||||||
|
fmt.Println("Hei maailma!")
|
||||||
|
|
||||||
|
// Kutsu toista funktiota tämän paketin sisällä.
|
||||||
|
beyondHello()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Funktioilla voi olla parametrejä sulkeissa.
|
||||||
|
// Vaikkei parametrejä olisikaan, sulkeet ovat silti pakolliset.
|
||||||
|
func beyondHello() {
|
||||||
|
var x int // Muuttujan ilmoittaminen: ne täytyy ilmoittaa ennen käyttöä.
|
||||||
|
x = 3 // Arvon antaminen muuttujalle.
|
||||||
|
// "Lyhyet" ilmoitukset käyttävät := joka päättelee tyypin, ilmoittaa
|
||||||
|
// sekä antaa arvon muuttujalle.
|
||||||
|
y := 4
|
||||||
|
sum, prod := learnMultiple(x, y) // Funktio palauttaa kaksi arvoa.
|
||||||
|
fmt.Println("summa:", sum, "tulo:", prod) // Yksinkertainen tuloste.
|
||||||
|
learnTypes() // < y minuuttia, opi lisää!
|
||||||
|
}
|
||||||
|
|
||||||
|
/* <- usean rivin kommentti
|
||||||
|
Funktioilla voi olla parametrejä ja (useita!) palautusarvoja.
|
||||||
|
Tässä `x`, `y` ovat argumenttejä ja `sum`, `prod` ovat ne, mitä palautetaan.
|
||||||
|
Huomaa että `x` ja `sum` saavat tyyin `int`.
|
||||||
|
*/
|
||||||
|
func learnMultiple(x, y int) (sum, prod int) {
|
||||||
|
return x + y, x * y // Palauta kaksi arvoa.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sisäänrakennettuja tyyppejä ja todellisarvoja.
|
||||||
|
func learnTypes() {
|
||||||
|
// Lyhyt ilmoitus antaa yleensä haluamasi.
|
||||||
|
str := "Opi Go!" // merkkijonotyyppi.
|
||||||
|
|
||||||
|
s2 := `"raaka" todellisarvoinen merrkijono
|
||||||
|
voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi.
|
||||||
|
|
||||||
|
// Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8.
|
||||||
|
g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen.
|
||||||
|
|
||||||
|
f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku.
|
||||||
|
c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla.
|
||||||
|
|
||||||
|
// var -syntaksi alkuarvoilla.
|
||||||
|
var u uint = 7 // Etumerkitön, toteutus riippuvainen koosta kuten int.
|
||||||
|
var pi float32 = 22. / 7
|
||||||
|
|
||||||
|
// Muuntosyntaksi lyhyellä ilmoituksella.
|
||||||
|
n := byte('\n') // byte on leminimi uint8:lle.
|
||||||
|
|
||||||
|
// Listoilla on kiinteä koko kääntöhetkellä.
|
||||||
|
var a4 [4]int // 4 int:in lista, alkiot ovat alustettu nolliksi.
|
||||||
|
a3 := [...]int{3, 1, 5} // Listan alustaja jonka kiinteäksi kooksi tulee 3
|
||||||
|
// alkiota, jotka saavat arvot 3, 1, ja 5.
|
||||||
|
|
||||||
|
// Siivuilla on muuttuva koko. Sekä listoilla että siivuilla on puolensa,
|
||||||
|
// mutta siivut ovat yleisempiä käyttötapojensa vuoksi.
|
||||||
|
s3 := []int{4, 5, 9} // Vertaa a3: ei sananheittoa (...).
|
||||||
|
s4 := make([]int, 4) // Varaa 4 int:n siivun, alkiot alustettu nolliksi.
|
||||||
|
var d2 [][]float64 // Vain ilmoitus, muistia ei varata.
|
||||||
|
bs := []byte("a slice") // Tyypinmuuntosyntaksi.
|
||||||
|
|
||||||
|
// Koska siivut ovat dynaamisia, niitä voidaan yhdistellä sellaisinaan.
|
||||||
|
// Lisätäksesi alkioita siivuun, käytä sisäänrakennettua append()-funktiota.
|
||||||
|
// Ensimmäinen argumentti on siivu, johon alkoita lisätään.
|
||||||
|
s := []int{1, 2, 3} // Tuloksena on kolmen alkion pituinen lista.
|
||||||
|
s = append(s, 4, 5, 6) // Lisätty kolme alkiota. Siivun pituudeksi tulee 6.
|
||||||
|
fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6]
|
||||||
|
|
||||||
|
// Lisätäksesi siivun toiseen voit antaa append-funktiolle referenssin
|
||||||
|
// siivuun tai todellisarvoiseen siivuun lisäämällä sanaheiton argumentin
|
||||||
|
// perään. Tämä tapa purkaa siivun alkiot ja lisää ne siivuun s.
|
||||||
|
s = append(s, []int{7, 8, 9}...) // 2. argumentti on todellisarvoinen siivu.
|
||||||
|
fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6 7 8 9]
|
||||||
|
|
||||||
|
p, q := learnMemory() // Ilmoittaa p ja q olevan tyyppiä osoittaja int:iin.
|
||||||
|
fmt.Println(*p, *q) // * seuraa osoittajaa. Tämä tulostaa kaksi int:ä.
|
||||||
|
|
||||||
|
// Kartat ovat dynaamisesti kasvavia assosiatiivisia listoja, kuten hash tai
|
||||||
|
// dictionary toisissa kielissä.
|
||||||
|
m := map[string]int{"three": 3, "four": 4}
|
||||||
|
m["one"] = 1
|
||||||
|
|
||||||
|
// Käyttämättömät muuttujat ovat virheitä Go:ssa.
|
||||||
|
// Alaviiva antaa sinun "käyttää" muuttujan mutta hylätä sen arvon.
|
||||||
|
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
|
||||||
|
// Tulostaminen tietysti lasketaan muuttujan käyttämiseksi.
|
||||||
|
fmt.Println(s, c, a4, s3, d2, m)
|
||||||
|
|
||||||
|
learnFlowControl() // Takaisin flowiin.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go:ssa on useista muista kielistä poiketen mahdollista käyttää nimettyjä
|
||||||
|
// palautusarvoja.
|
||||||
|
// Nimen antaminen palautettavan arvon tyypille funktion ilmoitusrivillä
|
||||||
|
// mahdollistaa helpon palaamisen useasta eri funktion suorituskohdasta sekä
|
||||||
|
// pelkän return-lausekkeen käytön ilman muita mainintoja.
|
||||||
|
func learnNamedReturns(x, y int) (z int) {
|
||||||
|
z = x * y
|
||||||
|
return // z on epäsuorasti tässä, koska nimesimme sen aiemmin.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go kerää kaikki roskansa. Siinä on osoittajia mutta ei niiden laskentoa.
|
||||||
|
// Voit tehdä virheen mitättömällä osoittajalla, mutta et
|
||||||
|
// kasvattamalla osoittajaa.
|
||||||
|
func learnMemory() (p, q *int) {
|
||||||
|
// Nimetyillä palautusarvoilla p ja q on tyyppi osoittaja int:iin.
|
||||||
|
p = new(int) // Sisäänrakennettu funktio new varaa muistia.
|
||||||
|
// Varattu int on alustettu nollaksi, p ei ole enää mitätön.
|
||||||
|
s := make([]int, 20) // Varaa 20 int:ä yhteen kohtaan muistissa.
|
||||||
|
s[3] = 7 // Anna yhdelle niistä arvo.
|
||||||
|
r := -2 // Ilmoita toinen paikallinen muuttuja.
|
||||||
|
return &s[3], &r // & ottaa asian osoitteen muistissa.
|
||||||
|
}
|
||||||
|
|
||||||
|
func expensiveComputation() float64 {
|
||||||
|
return m.Exp(10)
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnFlowControl() {
|
||||||
|
// If -lausekkeet vaativat aaltosulkeet mutta ei tavallisia sulkeita.
|
||||||
|
if true {
|
||||||
|
fmt.Println("mitä mä sanoin")
|
||||||
|
}
|
||||||
|
// Muotoilu on standardoitu käyttämällä komentorivin komentoa "go fmt".
|
||||||
|
if false {
|
||||||
|
// Nyrpistys.
|
||||||
|
} else {
|
||||||
|
// Nautinto.
|
||||||
|
}
|
||||||
|
// Käytä switch -lauseketta ketjutettujen if -lausekkeiden sijasta.
|
||||||
|
x := 42.0
|
||||||
|
switch x {
|
||||||
|
case 0:
|
||||||
|
case 1:
|
||||||
|
case 42:
|
||||||
|
// Tapaukset eivät "tipu läpi".
|
||||||
|
/*
|
||||||
|
Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso:
|
||||||
|
https://github.com/golang/go/wiki/Switch#fall-through
|
||||||
|
*/
|
||||||
|
case 43:
|
||||||
|
// Saavuttamaton.
|
||||||
|
default:
|
||||||
|
// Oletustapaus (default) on valinnainen.
|
||||||
|
}
|
||||||
|
// Kuten if, for -lauseke ei myöskään käytä tavallisia sulkeita.
|
||||||
|
// for- ja if- lausekkeissa ilmoitetut muuttujat ovat paikallisia niiden
|
||||||
|
// piireissä.
|
||||||
|
for x := 0; x < 3; x++ { // ++ on lauseke. Sama kuin "x = x + 1".
|
||||||
|
fmt.Println("iteraatio", x)
|
||||||
|
}
|
||||||
|
// x == 42 tässä.
|
||||||
|
|
||||||
|
// For on kielen ainoa silmukkalauseke mutta sillä on vaihtoehtosia muotoja.
|
||||||
|
for { // Päättymätön silmukka.
|
||||||
|
break // Kunhan vitsailin.
|
||||||
|
continue // Saavuttamaton.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Voit käyttää range -lauseketta iteroidaksesi listojen, siivujen, merkki-
|
||||||
|
// jonojen, karttojen tai kanavien läpi. range palauttaa yhden (kanava) tai
|
||||||
|
// kaksi arvoa (lista, siivu, merkkijono ja kartta).
|
||||||
|
for key, value := range map[string]int{"yksi": 1, "kaksi": 2, "kolme": 3} {
|
||||||
|
// jokaista kartan paria kohden, tulosta avain ja arvo
|
||||||
|
fmt.Printf("avain=%s, arvo=%d\n", key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kuten for -lausekkeessa := if -lausekkeessa tarkoittaa ilmoittamista ja
|
||||||
|
// arvon asettamista.
|
||||||
|
// Aseta ensin y, sitten testaa onko y > x.
|
||||||
|
if y := expensiveComputation(); y > x {
|
||||||
|
x = y
|
||||||
|
}
|
||||||
|
// Todellisarvoiset funktiot ovat sulkeumia.
|
||||||
|
xBig := func() bool {
|
||||||
|
return x > 10000 // Viittaa ylempänä ilmoitettuun x:ään.
|
||||||
|
}
|
||||||
|
fmt.Println("xBig:", xBig()) // tosi (viimeisin arvo on e^10).
|
||||||
|
x = 1.3e3 // Tämä tekee x == 1300
|
||||||
|
fmt.Println("xBig:", xBig()) // epätosi nyt.
|
||||||
|
|
||||||
|
// Lisäksi todellisarvoiset funktiot voidaan samalla sekä ilmoittaa että
|
||||||
|
// kutsua, jolloin niitä voidaan käyttää funtioiden argumentteina kunhan:
|
||||||
|
// a) todellisarvoinen funktio kutsutaan välittömästi (),
|
||||||
|
// b) palautettu tyyppi vastaa odotettua argumentin tyyppiä.
|
||||||
|
fmt.Println("Lisää ja tuplaa kaksi numeroa: ",
|
||||||
|
func(a, b int) int {
|
||||||
|
return (a + b) * 2
|
||||||
|
}(10, 2)) // Kutsuttu argumenteilla 10 ja 2
|
||||||
|
// => Lisää ja tuplaa kaksi numeroa: 24
|
||||||
|
|
||||||
|
// Kun tarvitset sitä, rakastat sitä.
|
||||||
|
goto love
|
||||||
|
love:
|
||||||
|
|
||||||
|
learnFunctionFactory() // Funktioita palauttavat funktiot
|
||||||
|
learnDefer() // Nopea kiertoreitti tärkeään avainsanaan.
|
||||||
|
learnInterfaces() // Hyvää kamaa tulossa!
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnFunctionFactory() {
|
||||||
|
// Seuraavat kaksi ovat vastaavia, mutta toinen on käytännöllisempi
|
||||||
|
fmt.Println(sentenceFactory("kesä")("Kaunis", "päivä!"))
|
||||||
|
|
||||||
|
d := sentenceFactory("kesä")
|
||||||
|
fmt.Println(d("Kaunis", "päivä!"))
|
||||||
|
fmt.Println(d("Laiska", "iltapäivä!"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Somisteet ovat yleisiä toisissa kielissä. Sama saavutetaan Go:ssa käyttämällä
|
||||||
|
// todellisarvoisia funktioita jotka ottavat vastaan argumentteja.
|
||||||
|
func sentenceFactory(mystring string) func(before, after string) string {
|
||||||
|
return func(before, after string) string {
|
||||||
|
return fmt.Sprintf("%s %s %s", before, mystring, after) // uusi jono
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnDefer() (ok bool) {
|
||||||
|
// Lykätyt lausekkeet suoritetaan juuri ennen funktiosta palaamista.
|
||||||
|
defer fmt.Println("lykätyt lausekkeet suorittuvat")
|
||||||
|
defer fmt.Println("käänteisessä järjestyksessä (LIFO).")
|
||||||
|
defer fmt.Println("\nTämä rivi tulostuu ensin, koska")
|
||||||
|
// Defer -lauseketta käytetään yleisesti tiedoston sulkemiseksi, jotta
|
||||||
|
// tiedoston sulkeva funktio pysyy lähellä sen avannutta funktiota.
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Määrittele Stringer rajapintatyypiksi jolla on
|
||||||
|
// yksi jäsenfunktio eli metodi, String.
|
||||||
|
type Stringer interface {
|
||||||
|
String() string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Määrittele pair rakenteeksi jossa on kaksi kenttää, x ja y tyyppiä int.
|
||||||
|
type pair struct {
|
||||||
|
x, y int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Määrittele jäsenfunktio pair:lle. Pair tyydyttää nyt Stringer -rajapinnan.
|
||||||
|
func (p pair) String() string { // p:tä kutsutaan nimellä "receiver"
|
||||||
|
// Sprintf on toinen julkinen funktio paketissa fmt.
|
||||||
|
// Pistesyntaksilla viitataan P:n kenttiin.
|
||||||
|
return fmt.Sprintf("(%d, %d)", p.x, p.y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnInterfaces() {
|
||||||
|
// Aaltosuljesyntaksi on "todellisarvoinen rakenne". Se todentuu alustetuksi
|
||||||
|
// rakenteeksi. := -syntaksi ilmoittaa ja alustaa p:n täksi rakenteeksi.
|
||||||
|
p := pair{3, 4}
|
||||||
|
fmt.Println(p.String()) // Kutsu p:n (tyyppiä pair) jäsenfunktiota String.
|
||||||
|
var i Stringer // Ilmoita i Stringer-rajapintatyypiksi.
|
||||||
|
i = p // Pätevä koska pair tyydyttää rajapinnan Stringer.
|
||||||
|
// Kutsu i:n (Stringer) jäsenfunktiota String. Tuloste on sama kuin yllä.
|
||||||
|
fmt.Println(i.String())
|
||||||
|
|
||||||
|
// Funktiot fmt-paketissa kutsuvat argumenttien String-jäsenfunktiota
|
||||||
|
// selvittääkseen onko niistä saatavilla tulostettavaa vastinetta.
|
||||||
|
fmt.Println(p) // Tuloste on sama kuin yllä. Println kutsuu String-metodia.
|
||||||
|
fmt.Println(i) // Tuloste on sama kuin yllä.
|
||||||
|
|
||||||
|
learnVariadicParams("loistavaa", "oppimista", "täällä!")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Funktioilla voi olla muuttuva eli variteettinen
|
||||||
|
// määrä argumentteja eli parametrejä.
|
||||||
|
func learnVariadicParams(myStrings ...interface{}) {
|
||||||
|
// Iteroi jokaisen argumentin läpi.
|
||||||
|
// Tässä alaviivalla sivuutetaan argumenttilistan kunkin kohdan indeksi.
|
||||||
|
for _, param := range myStrings {
|
||||||
|
fmt.Println("param:", param)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Luovuta variteettinen arvo variteettisena parametrinä.
|
||||||
|
fmt.Println("params:", fmt.Sprintln(myStrings...))
|
||||||
|
|
||||||
|
learnErrorHandling()
|
||||||
|
}
|
||||||
|
|
||||||
|
func learnErrorHandling() {
|
||||||
|
// "; ok" -muotoa käytetään selvittääksemme toimiko jokin vai ei.
|
||||||
|
m := map[int]string{3: "kolme", 4: "neljä"}
|
||||||
|
if x, ok := m[1]; !ok { // ok on epätosi koska 1 ei ole kartassa.
|
||||||
|
fmt.Println("ei ketään täällä")
|
||||||
|
} else {
|
||||||
|
fmt.Print(x) // x olisi arvo jos se olisi kartassa.
|
||||||
|
}
|
||||||
|
// Virhearvo voi kertoa muutakin ongelmasta.
|
||||||
|
if _, err := strconv.Atoi("ei-luku"); err != nil { // _ sivuuttaa arvon
|
||||||
|
// tulostaa strconv.ParseInt: parsing "ei-luku": invalid syntax
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
// Palaamme rajapintoihin hieman myöhemmin. Sillä välin,
|
||||||
|
learnConcurrency()
|
||||||
|
}
|
||||||
|
|
||||||
|
// c on kanava, samanaikaisturvallinen viestintäolio.
|
||||||
|
func inc(i int, c chan int) {
|
||||||
|
c <- i + 1 // <- on "lähetysoperaattori" kun kanava on siitä vasemmalla.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Käytämme inc -funktiota samanaikaiseen lukujen lisäämiseen.
|
||||||
|
func learnConcurrency() {
|
||||||
|
// Sama make -funktio jota käytimme aikaisemmin siivun luomiseksi. Make
|
||||||
|
// varaa muistin ja alustaa siivut, kartat ja kanavat.
|
||||||
|
c := make(chan int)
|
||||||
|
// Aloita kolme samanaikaista gorutiinia (goroutine). Luvut kasvavat
|
||||||
|
// samanaikaisesti ja ehkäpä rinnakkain jos laite on kykenevä ja oikein
|
||||||
|
// määritelty. Kaikki kolme lähettävät samalle kanavalle.
|
||||||
|
go inc(0, c) // go -lauseke aloittaa uuden gorutiinin.
|
||||||
|
go inc(10, c)
|
||||||
|
go inc(-805, c)
|
||||||
|
// Lue kolme palautusarvoa kanavalta ja tulosta ne.
|
||||||
|
// Niiden saapumisjärjestystä ei voida taata!
|
||||||
|
// <- on "vastaanotto-operaattori" jos kanava on oikealla
|
||||||
|
fmt.Println(<-c, <-c, <-c)
|
||||||
|
|
||||||
|
cs := make(chan string) // Toinen kanava joka käsittelee merkkijonoja.
|
||||||
|
ccs := make(chan chan string) // Kanava joka käsittelee merkkijonokanavia.
|
||||||
|
go func() { c <- 84 }() // Aloita uusi gorutiini arvon lähettämiseksi.
|
||||||
|
go func() { cs <- "sanaa" }() // Uudestaan, mutta cs -kanava tällä kertaa.
|
||||||
|
// Select -lausekkeella on syntaksi kuten switch -lausekkeella mutta
|
||||||
|
// jokainen tapaus sisältää kanavaoperaation. Se valitsee satunnaisen
|
||||||
|
// tapauksen niistä kanavista, jotka ovat kommunikaatiovalmiita
|
||||||
|
select {
|
||||||
|
case i := <-c: // Vastaanotettu arvo voidaan antaa muuttujalle
|
||||||
|
fmt.Printf("se on %T", i)
|
||||||
|
case <-cs: // tai vastaanotettu arvo voidaan sivuuttaa.
|
||||||
|
fmt.Println("se on merkkijono")
|
||||||
|
case <-ccs: // Tyhjä kanava; ei valmis kommunikaatioon.
|
||||||
|
fmt.Println("ei tapahtunut.")
|
||||||
|
}
|
||||||
|
// Tässä vaiheessa arvo oli otettu joko c:ltä tai cs:ltä. Yksi kahdesta
|
||||||
|
// ylempänä aloitetusta gorutiinista on valmistunut, toinen pysyy tukossa.
|
||||||
|
|
||||||
|
learnWebProgramming() // Go tekee sitä. Sinäkin haluat tehdä sitä.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Yksittäinen funktio http -paketista aloittaa web-palvelimen.
|
||||||
|
func learnWebProgramming() {
|
||||||
|
|
||||||
|
// ListenAndServe:n ensimmäinen parametri on TCP-osoite, jota kuunnellaan.
|
||||||
|
// Toinen parametri on rajapinta, http.Handler.
|
||||||
|
go func() {
|
||||||
|
err := http.ListenAndServe(":8080", pair{})
|
||||||
|
fmt.Println(err) // älä sivuuta virheitä.
|
||||||
|
}()
|
||||||
|
|
||||||
|
requestServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tee pair:sta http.Handler implementoimalla sen ainoa metodi, ServeHTTP.
|
||||||
|
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Tarjoa dataa metodilla http.ResponseWriter.
|
||||||
|
w.Write([]byte("Opit Go:n Y minuutissa!"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestServer() {
|
||||||
|
resp, err := http.Get("http://localhost:8080")
|
||||||
|
fmt.Println(err)
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
|
fmt.Printf("\nWeb-palvelin sanoo: `%s`", string(body))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Lisää luettavaa
|
||||||
|
|
||||||
|
Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/).
|
||||||
|
Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon.
|
||||||
|
Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa
|
||||||
|
siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta.
|
||||||
|
|
||||||
|
Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja
|
||||||
|
yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.)
|
||||||
|
|
||||||
|
Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm).
|
||||||
|
Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org)
|
||||||
|
[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista.
|
||||||
|
|
||||||
|
Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/).
|
||||||
|
Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista,
|
||||||
|
-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja
|
||||||
|
lähdekoodi tulee esille!
|
||||||
|
|
||||||
|
Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/).
|
||||||
|
|
||||||
|
Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia
|
||||||
|
Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile).
|
259
fi-fi/markdown-fi.html.markdown
Normal file
259
fi-fi/markdown-fi.html.markdown
Normal file
@ -0,0 +1,259 @@
|
|||||||
|
---
|
||||||
|
language: markdown
|
||||||
|
filename: markdown-fi.md
|
||||||
|
contributors:
|
||||||
|
- ["Dan Turkel", "http://danturkel.com/"]
|
||||||
|
translators:
|
||||||
|
- ["Timo Virkkunen", "https://github.com/ComSecNinja"]
|
||||||
|
lang: fi-fi
|
||||||
|
---
|
||||||
|
|
||||||
|
John Gruber loi Markdownin vuona 2004. Sen tarkoitus on olla helposti luettava ja kirjoitettava syntaksi joka muuntuu helposti HTML:ksi (ja nyt myös moneksi muuksi formaatiksi).
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
<!-- Jokainen HTML-tiedosto on pätevää Markdownia. Tämä tarkoittaa että voimme
|
||||||
|
käyttää HTML-elementtejä Markdownissa, kuten kommentteja, ilman että markdown
|
||||||
|
-jäsennin vaikuttaa niihin. Tästä johtuen et voi kuitenkaan käyttää markdownia
|
||||||
|
HTML-elementtien sisällä jos luot sellaisen markdown-tiedostoon. -->
|
||||||
|
|
||||||
|
<!-- Markdownin toteutus vaihtelee jäsentimestä toiseen. Tämä opas yrittää
|
||||||
|
selventää mitkä ominaisuudet ovat yleisiä ja mitkä ovat eritysesti tiettyjen
|
||||||
|
jäsentimien ominaisuuksia. -->
|
||||||
|
|
||||||
|
<!-- Otsikot -->
|
||||||
|
<!-- Voit luoda HTML-elementtejä <h1> - <h6> helposti aloittamalla rivin
|
||||||
|
haluamallasi määrällä ristikkomerkkejä (#). -->
|
||||||
|
# Tämä on <h1>
|
||||||
|
## Tämä on <h2>
|
||||||
|
### Tämä on <h3>
|
||||||
|
#### Tämä on <h4>
|
||||||
|
##### Tämä on <h5>
|
||||||
|
###### Tämä on <h6>
|
||||||
|
|
||||||
|
<!-- Markdownissa on myös vaihtoehtoisia tapoja ilmaista h1 ja h2. -->
|
||||||
|
Tämä on h1
|
||||||
|
=============
|
||||||
|
|
||||||
|
Tämä on h2
|
||||||
|
-------------
|
||||||
|
|
||||||
|
<!-- Yksinkertaiset tekstimuotoilut -->
|
||||||
|
<!-- Tekstin voi helposti muotoilla kursiiviksi tai lihavoiduksi. -->
|
||||||
|
|
||||||
|
*Tämä teksti on kursivoitua.*
|
||||||
|
_Kuten on myös tämä teksti._
|
||||||
|
|
||||||
|
**Tämä teksti on lihavoitua.**
|
||||||
|
__Kuten on tämäkin teksti.__
|
||||||
|
|
||||||
|
***Tämä teksti on molempia.***
|
||||||
|
**_Kuten tämäkin!_**
|
||||||
|
*__Kuten tämäkin!__*
|
||||||
|
|
||||||
|
<!-- Github-tyylisessä Markdownissa, jota käytetään tiedostojen esittämiseksi
|
||||||
|
Githubissa, meillä on käytössämme myös yliviivaus: -->
|
||||||
|
|
||||||
|
~~Tämä teksti on yliviivattua.~~
|
||||||
|
|
||||||
|
<!-- Kappaleet ovat yhdellä tai useammalla peräkkäisellä tekstirivillä jotka
|
||||||
|
erotellaan yhdellä tai useammalla tyhjällä rivillä -->
|
||||||
|
|
||||||
|
Tämä on kappala. Kirjoittelen kappaleeseen, eikö tämä olekin hauskaa?
|
||||||
|
|
||||||
|
Nyt olen kappaleessa 2.
|
||||||
|
Olen edelleen toisessa kappaleessa!
|
||||||
|
|
||||||
|
|
||||||
|
Olen kolmannessa kappaleessa!
|
||||||
|
|
||||||
|
<!-- Jos haluat lisätä <br /> HTML-elementin, päätä kappale kahdella tai
|
||||||
|
useammalla välilyönnillä ja aloita sitten uusi kappale -->
|
||||||
|
|
||||||
|
Päätän tämän kahteen välilyöntiin (maalaa minut nähdäksesi ne).
|
||||||
|
|
||||||
|
There's a <br /> above me!
|
||||||
|
|
||||||
|
<!-- Lainaukset ovat helppoja ja ne tehdään >-merkillä -->
|
||||||
|
|
||||||
|
> Tämä on lainaus. Voit joko
|
||||||
|
> manuaalisesti rivittää tekstisi ja laittaa >-merkin jokaisen rivin eteen tai antaa jäsentimen rivittää pitkät tekstirivit.
|
||||||
|
> Sillä ei ole merkitystä kunhan rivit alkavat >-merkillä.
|
||||||
|
|
||||||
|
> Voit myös käyttää useampaa
|
||||||
|
>> sisennystasoa
|
||||||
|
> Kuinka hienoa se on?
|
||||||
|
|
||||||
|
<!-- Listat -->
|
||||||
|
<!-- Järjestämättömät listat tehdään asteriskilla, plussalla tai viivalla -->
|
||||||
|
|
||||||
|
* Kohta
|
||||||
|
* Kohta
|
||||||
|
* Kolmas kohta
|
||||||
|
|
||||||
|
tai
|
||||||
|
|
||||||
|
+ Kohta
|
||||||
|
+ Kohta
|
||||||
|
+ Kolmas kohta
|
||||||
|
|
||||||
|
tai
|
||||||
|
|
||||||
|
- Kohta
|
||||||
|
- Kohta
|
||||||
|
- Kolmas kohta
|
||||||
|
|
||||||
|
<!-- Järjestetyt listat tehdään järjestysluvuilla. -->
|
||||||
|
|
||||||
|
1. Kohta yksi
|
||||||
|
2. Kohta kaksi
|
||||||
|
3. Kohta kolme
|
||||||
|
|
||||||
|
<!-- Sinun ei tarvitse edes merkitä kohtia oikein ja silti markdown näyttää
|
||||||
|
oikean järjestyksen, mutta se ei välttämättä ole hyvä idea. -->
|
||||||
|
|
||||||
|
1. Kohta yksi
|
||||||
|
1. Kohta kaksi
|
||||||
|
1. Kohta kolme
|
||||||
|
<!-- (Tämä korjaantuu samanlaiseksi kuin yllä oleva esimerkki) -->
|
||||||
|
|
||||||
|
<!-- Voit myös käyttää alalistoja. -->
|
||||||
|
|
||||||
|
1. Kohta yksi
|
||||||
|
2. Kohta kaksi
|
||||||
|
3. Kohta kolme
|
||||||
|
* Alakohta
|
||||||
|
* Alakohta
|
||||||
|
4. Kohta neljä
|
||||||
|
|
||||||
|
<!-- Myös tehtävälistoja on olemassa. Tämä tekee HTML-valintaruutuja. -->
|
||||||
|
|
||||||
|
Alla olevat ruudut ilman x-merkkiä ovat merkitsemättömiä HTML-valintaruutuja.
|
||||||
|
- [ ] Ensimmäinen suoritettava tehtävä.
|
||||||
|
- [ ] Toinen tehtävä joka täytyy tehdä
|
||||||
|
Tämä alla oleva ruutu on merkitty HTML-valintaruutu.
|
||||||
|
- [x] Tämä tehtävä on suoritettu
|
||||||
|
|
||||||
|
<!-- Koodiosiot -->
|
||||||
|
<!-- Voit merkitä koodiosion (jaka käyttää <code> -elementtiä) sisentämällä
|
||||||
|
rivin neljällä välilyönnillä tai tabulaattorilla. -->
|
||||||
|
|
||||||
|
Tämä on koodia
|
||||||
|
Kuten tämäkin
|
||||||
|
|
||||||
|
<!-- Voit myös sisentää koodia samalla tavalla. -->
|
||||||
|
|
||||||
|
my_array.each do |item|
|
||||||
|
puts item
|
||||||
|
end
|
||||||
|
|
||||||
|
<!-- Muun tekstin seassa oleva koodi merkitään kahden `-merkin väliin -->
|
||||||
|
|
||||||
|
John ei tiennyt edes mitä `go_to()` -funktio teki!
|
||||||
|
|
||||||
|
<!-- Githubin Markdownissa voit käyttää erityissyntaksia koodille. -->
|
||||||
|
|
||||||
|
\`\`\`ruby <!-- paitsi että poista nuo kenoviivat, vain ```ruby ! -->
|
||||||
|
def foobar
|
||||||
|
puts "Hello world!"
|
||||||
|
end
|
||||||
|
\`\`\` <!-- tästä myös, ei kenoviivoja, vain ``` -->
|
||||||
|
|
||||||
|
<!-- Yllä oleva teksti ei vaadi sisennystä. Lisäksi Github käyttää ``` jälkeen
|
||||||
|
mainitsemasi kielen syntaksin korostusta -->
|
||||||
|
|
||||||
|
<!-- Vaakaviiva (<hr />) -->
|
||||||
|
<!-- Vaakaviivojen lisääminen käy näppärästi kolmella tai useammalla
|
||||||
|
asteriskilla taikka viivalla, välilyönneillä tai ilman -->
|
||||||
|
|
||||||
|
***
|
||||||
|
---
|
||||||
|
- - -
|
||||||
|
****************
|
||||||
|
|
||||||
|
<!-- Linkit -->
|
||||||
|
<!-- yksi markdownin parhaita ominaisuuksia on yksinkertaiset hyperlinkit. Laita
|
||||||
|
näytettävä teksti hakasulkuihin [] ja URL-osoite perään sulkeissa (). -->
|
||||||
|
|
||||||
|
[Klikkaa tästä!](http://example.com/)
|
||||||
|
|
||||||
|
<!-- Voit myös lisätä linkin otsikon heittomerkeissä osoitteen perään. -->
|
||||||
|
|
||||||
|
[Klikkaa tästä!](http://example.com/ "Linkki Example.com:iin")
|
||||||
|
|
||||||
|
<!-- Suhteelliset polut toimivat myös. -->
|
||||||
|
|
||||||
|
[Musiikkia](/musiikki/).
|
||||||
|
|
||||||
|
<!-- Markdown tukee myös viittaustyylisiä linkkejä. -->
|
||||||
|
|
||||||
|
[Klikkaa tätä linkkiä][link1] saadaksesi lisätietoja!
|
||||||
|
[Katso myös tämä linkki][foobar] jos haluat.
|
||||||
|
|
||||||
|
[link1]: http://example.com/ "Siistii!"
|
||||||
|
[foobar]: http://foobar.biz/ "Selkis!"
|
||||||
|
|
||||||
|
<!-- Otsikko voi olla myös ykittäisissä heittomerkeissä tai sulkeissa, tai
|
||||||
|
ohitettu kokonaan. Viittaukset voivat olla missä tahansa kohdassa dokumenttia ja
|
||||||
|
viittausten ID:t voivat olla mitä tahansa kunhan ne ovat uniikkeja. -->
|
||||||
|
|
||||||
|
<!-- Voit myös käyttää linkin tekstiä ID:nä näin: -->
|
||||||
|
|
||||||
|
[This][] is a link.
|
||||||
|
|
||||||
|
[this]: http://tämäonlinkki.com/
|
||||||
|
|
||||||
|
<!-- Mutta tämä tapa ei ole yleinen. -->
|
||||||
|
|
||||||
|
<!-- Kuvat -->
|
||||||
|
<!-- Kuvat tehdään samalla tavalla kuin linkitkin, mutta huutomerkki edessä! -->
|
||||||
|
|
||||||
|
![Kuvan alt-attribuutti](http://imgur.com/munkuva.jpg "Vaihtoehtoinen otsikko")
|
||||||
|
|
||||||
|
<!-- Ja viittaukset toimivat odotetusti. -->
|
||||||
|
|
||||||
|
![Tämä on se alt-attribuutti][munkuva]
|
||||||
|
|
||||||
|
[munkuva]: suhteellinen/polku/siitii/kuva.jpg "otsikko tähän tarvittaessa"
|
||||||
|
|
||||||
|
<!-- Sekalaista -->
|
||||||
|
<!-- Automaattiset linkit -->
|
||||||
|
|
||||||
|
<http://testwebsite.com/> on sama kuin
|
||||||
|
[http://testwebsite.com/](http://testwebsite.com/)
|
||||||
|
|
||||||
|
<!-- Automaattiset sähköpostilinkit -->
|
||||||
|
|
||||||
|
<foo@bar.com>
|
||||||
|
|
||||||
|
<!-- Varattujen merkkien käyttö -->
|
||||||
|
|
||||||
|
haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en halua
|
||||||
|
sen kursivoituvan, joten teen näin: \*tämän tekstin ympärillä on asteriskit\*.
|
||||||
|
|
||||||
|
<!-- Näppäimistön näppäimet -->
|
||||||
|
<!-- Githubin Markdownissa, voit käyttää <kbd> -tagia esittämään näppäimiä -->
|
||||||
|
|
||||||
|
Tietokoneesi kaatui? Kokeile painaa
|
||||||
|
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||||
|
|
||||||
|
<!-- Taulukot -->
|
||||||
|
<!-- Taulukot ovat saatavilla vain Githubin markdownissa ja ne ovat melko
|
||||||
|
vaivalloisia käyttää, mutta jos todella haluat: -->
|
||||||
|
|
||||||
|
| Kolumni1 | Kolumni2 | Kolumni3 |
|
||||||
|
| :----------- | :------: | ------------: |
|
||||||
|
| Vasemmalle | Keskelle | Oikealle |
|
||||||
|
| blaa | blaa | blaa |
|
||||||
|
|
||||||
|
<!-- vaihtoehtoisesti, sama tulos -->
|
||||||
|
|
||||||
|
Kolumni 1 | Kolumni 2 | Kolumni 3
|
||||||
|
:-- | :-: | --:
|
||||||
|
Hyi tämä on ruma | saa se | loppumaan
|
||||||
|
|
||||||
|
<!-- Loppu! -->
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Lisää tietoa löydät John Gruberin [virallisesta julkaisusta](http://daringfireball.net/projects/markdown/syntax)
|
||||||
|
ja Adam Pritchardin loistavasta [lunttilapusta](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
608
fi-fi/ruby-fi.html.markdown
Normal file
608
fi-fi/ruby-fi.html.markdown
Normal file
@ -0,0 +1,608 @@
|
|||||||
|
---
|
||||||
|
language: ruby
|
||||||
|
filename: learnruby-fi.rb
|
||||||
|
contributors:
|
||||||
|
- ["David Underwood", "http://theflyingdeveloper.com"]
|
||||||
|
- ["Joel Walden", "http://joelwalden.net"]
|
||||||
|
- ["Luke Holder", "http://twitter.com/lukeholder"]
|
||||||
|
- ["Tristan Hume", "http://thume.ca/"]
|
||||||
|
- ["Nick LaMuro", "https://github.com/NickLaMuro"]
|
||||||
|
- ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
|
||||||
|
- ["Ariel Krakowski", "http://www.learneroo.com"]
|
||||||
|
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
||||||
|
- ["Levi Bostian", "https://github.com/levibostian"]
|
||||||
|
- ["Rahil Momin", "https://github.com/iamrahil"]
|
||||||
|
- ["Gabriel Halley", "https://github.com/ghalley"]
|
||||||
|
- ["Persa Zula", "http://persazula.com"]
|
||||||
|
- ["Jake Faris", "https://github.com/farisj"]
|
||||||
|
translators:
|
||||||
|
- ["Oliver Vartiainen", "https://github.com/firoxer"]
|
||||||
|
lang: fi-fi
|
||||||
|
---
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
# Tässä yhden rivin kommentti
|
||||||
|
|
||||||
|
=begin
|
||||||
|
Tässä usean rivin kommentti
|
||||||
|
Näitä ei kylläkään käytetä
|
||||||
|
Joten käytetään vastedes vain yksirivisiä
|
||||||
|
=end
|
||||||
|
|
||||||
|
# Tärkeintä on muistaa, että Rubyssa kaikki pohjautuu olioihin.
|
||||||
|
|
||||||
|
# Luvutkin ovat olioita:
|
||||||
|
|
||||||
|
3.class #=> Fixnum
|
||||||
|
|
||||||
|
3.to_s #=> "3"
|
||||||
|
|
||||||
|
# Peruslaskutoimituksia:
|
||||||
|
1 + 1 #=> 2
|
||||||
|
8 - 1 #=> 7
|
||||||
|
10 * 2 #=> 20
|
||||||
|
35 / 5 #=> 7
|
||||||
|
2**5 #=> 32
|
||||||
|
5 % 3 #=> 2
|
||||||
|
|
||||||
|
# Bittioperaatioita:
|
||||||
|
3 & 5 #=> 1
|
||||||
|
3 | 5 #=> 7
|
||||||
|
3 ^ 5 #=> 6
|
||||||
|
|
||||||
|
# Laskutoimitukset ovat vain syntaksisokeria lukuolion laskumetodin kutsulle:
|
||||||
|
1.+(3) #=> 4
|
||||||
|
10.* 5 #=> 50
|
||||||
|
|
||||||
|
# Erityisarvotkin ovat olioita:
|
||||||
|
|
||||||
|
nil # vastaa joidenkin kielten "null"-arvoa
|
||||||
|
true # tosi
|
||||||
|
false # epätosi
|
||||||
|
|
||||||
|
nil.class #=> NilClass
|
||||||
|
true.class #=> TrueClass
|
||||||
|
false.class #=> FalseClass
|
||||||
|
|
||||||
|
# Samanvertaisuuden testaus:
|
||||||
|
1 == 1 #=> true
|
||||||
|
2 == 1 #=> false
|
||||||
|
|
||||||
|
# ...ja sama eriarvoisuudelle:
|
||||||
|
1 != 1 #=> false
|
||||||
|
2 != 1 #=> true
|
||||||
|
|
||||||
|
# "nil" ja "false" ovat ainoat epätodet arvot; kaikki muu ymmärretään todeksi:
|
||||||
|
!nil #=> true
|
||||||
|
!false #=> true
|
||||||
|
!0 #=> false
|
||||||
|
|
||||||
|
# Lisää vertailuoperaatioita:
|
||||||
|
1 < 10 #=> true
|
||||||
|
1 > 10 #=> false
|
||||||
|
2 <= 2 #=> true
|
||||||
|
2 >= 2 #=> true
|
||||||
|
|
||||||
|
# Kahdensuuntainen vertailuoperaattori:
|
||||||
|
1 <=> 10 #=> -1
|
||||||
|
10 <=> 1 #=> 1
|
||||||
|
1 <=> 1 #=> 0
|
||||||
|
|
||||||
|
# Logiikkaoperaattorit:
|
||||||
|
true && false #=> false
|
||||||
|
true || false #=> true
|
||||||
|
!true #=> false
|
||||||
|
|
||||||
|
# Merkkipohjaisten logiikkaoperaattorien vaihtoehtona on sanalliset muodot,
|
||||||
|
# joilla on hyvin matala presedenssi. Niillä voi muokata ohjelman kulkua
|
||||||
|
# esimerkiksi väitelausekkeita ketjuttaen.
|
||||||
|
|
||||||
|
# Metodia `do_something_else` kutsutaan vain, jos `do_something` onnistuu:
|
||||||
|
do_something() and do_something_else()
|
||||||
|
# Metodia `log_error` kutsutaan vain, jos `do_something` epäonnistuu:
|
||||||
|
do_something() or log_error()
|
||||||
|
|
||||||
|
# Merkkijonot ovat olioita:
|
||||||
|
|
||||||
|
'Tässä on merkkijono'.class #=> String
|
||||||
|
"Rajaavat lainausmerkit voivat olla yksin- tai kaksinkertaisia".class #=> String
|
||||||
|
|
||||||
|
täyte = 'sisällyttää muita merkkijonoja'
|
||||||
|
"Kaksinkertaisilla lainausmerkeillä voi #{täyte}"
|
||||||
|
#=> "Kaksinkertaisilla lainausmerkeillä voi sisällyttää muita merkkijonoja"
|
||||||
|
|
||||||
|
# Yksinkertaisia lainausmerkkejä kannattaa silti suosia, sillä kaksinkertaiset
|
||||||
|
# merkit saattavat aiheuttaa turhia kielensisäisiä tarkistuksia.
|
||||||
|
|
||||||
|
# Merkkijonoja voi yhdistellä toisiinsa:
|
||||||
|
'hello ' + 'world' #=> "hello world"
|
||||||
|
|
||||||
|
# ...mutta luvut vaativat ensin tyyppimuunnoksen:
|
||||||
|
'hello ' + 3 #=> TypeError: can't convert Fixnum into String
|
||||||
|
'hello ' + 3.to_s #=> "hello 3"
|
||||||
|
|
||||||
|
# Merkkijonoja voi soveltaa laskutoimituksiin... odotettavin seurauksin:
|
||||||
|
'hello ' * 3 #=> "hello hello hello "
|
||||||
|
|
||||||
|
# Merkkijonoa voi jatkaa toisella:
|
||||||
|
'hello' << ' world' #=> "hello world"
|
||||||
|
|
||||||
|
# Tulosteen luonti kera rivinvaihdon:
|
||||||
|
puts "I'm printing!"
|
||||||
|
#=> I'm printing!
|
||||||
|
#=> nil
|
||||||
|
|
||||||
|
# ...ja ilman rivinvaihtoa:
|
||||||
|
print "I'm printing!"
|
||||||
|
#=> I'm printing! => nil
|
||||||
|
|
||||||
|
# Muuttujien määrittely:
|
||||||
|
x = 25 #=> 25
|
||||||
|
x #=> 25
|
||||||
|
|
||||||
|
# Arvon asettaminen palauttaa arvon itsensä, joten usean muuttujan arvon
|
||||||
|
# yhtäaikainen määrittely käy vaivatta:
|
||||||
|
x = y = 10 #=> 10
|
||||||
|
x #=> 10
|
||||||
|
y #=> 10
|
||||||
|
|
||||||
|
# Muuttujien sanaerottimena käytetään alaviivaa:
|
||||||
|
snake_case = true
|
||||||
|
|
||||||
|
# Lisäksi Rubyssa suositaan ytimekkäitä nimiä:
|
||||||
|
path_to_project_root = '/good/name/'
|
||||||
|
path = '/bad/name/'
|
||||||
|
|
||||||
|
# Symbolit
|
||||||
|
|
||||||
|
# Symbolit ovat muuttumattomia, uudelleenkäytettäviä vakioita.
|
||||||
|
# Niitä käytetään merkkijonojen sijaan, kun tarkoitus on viitata arvoon,
|
||||||
|
# jolla on tietty, pysyvä merkitys:
|
||||||
|
|
||||||
|
:pending.class #=> Symbol
|
||||||
|
|
||||||
|
status = :pending
|
||||||
|
|
||||||
|
status == :pending #=> true
|
||||||
|
|
||||||
|
status == 'pending' #=> false
|
||||||
|
|
||||||
|
status == :approved #=> false
|
||||||
|
|
||||||
|
# Taulukot
|
||||||
|
|
||||||
|
# Tässä taulukko:
|
||||||
|
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
|
||||||
|
|
||||||
|
# Taulukko saa koostua erityyppisistä arvoista:
|
||||||
|
[1, 'hello', false] #=> [1, "hello", false]
|
||||||
|
|
||||||
|
# Taulukon alkioihin voi viitata järjestysnumerolla nollasta alkaen:
|
||||||
|
array[0] #=> 1
|
||||||
|
array.first #=> 1
|
||||||
|
array[12] #=> nil
|
||||||
|
|
||||||
|
# Kuten laskutoimituksissa nähty syntaksisokeri on myös taulukon alkioiden haku
|
||||||
|
# pohjimmiltaan vain taulukko-olioon kuuluvan "[]"-metodin kutsu:
|
||||||
|
array.[] 0 #=> 1
|
||||||
|
array.[] 12 #=> nil
|
||||||
|
|
||||||
|
# Haku käy myös lopustapäin:
|
||||||
|
array[-1] #=> 5
|
||||||
|
array.last #=> 5
|
||||||
|
|
||||||
|
# Alitaulukon haku käy indeksiparilla...
|
||||||
|
array[2, 3] #=> [3, 4, 5]
|
||||||
|
|
||||||
|
# ...tai määrittelemällä väli:
|
||||||
|
array[1..3] #=> [2, 3, 4]
|
||||||
|
|
||||||
|
# Taulukon voi kääntää:
|
||||||
|
a=[1,2,3]
|
||||||
|
a.reverse! #=> [3,2,1]
|
||||||
|
|
||||||
|
# Ja sitä voi jatkaa näin...
|
||||||
|
array << 6 #=> [1, 2, 3, 4, 5, 6]
|
||||||
|
|
||||||
|
# ...tai näin:
|
||||||
|
array.push(6) #=> [1, 2, 3, 4, 5, 6]
|
||||||
|
|
||||||
|
# Alkion olemassaolon tarkistus:
|
||||||
|
array.include?(1) #=> true
|
||||||
|
|
||||||
|
# Hashit eli assosiaatiotaulut ovat Rubyn tärkein avain-/arvoparirakenne.
|
||||||
|
# Hash luodaan aaltosulkeilla:
|
||||||
|
hash = { 'color' => 'green', 'number' => 5 }
|
||||||
|
|
||||||
|
hash.keys #=> ['color', 'number']
|
||||||
|
|
||||||
|
# Hash toimii erityisen nopeasti, kun haetaan arvoa avaimen perusteella:
|
||||||
|
hash['color'] #=> 'green'
|
||||||
|
hash['number'] #=> 5
|
||||||
|
|
||||||
|
# Jos hashistä ei löyty avainta vastaavaa arvoa, palautetaan nil-arvo:
|
||||||
|
hash['nothing here'] #=> nil
|
||||||
|
|
||||||
|
# Symbolihashin määrittelylle on oma syntaksinsa (alkaen Rubyn versiosta 1.9):
|
||||||
|
new_hash = { defcon: 3, action: true }
|
||||||
|
new_hash.keys #=> [:defcon, :action]
|
||||||
|
|
||||||
|
# Hashin avaimen ja arvon olemassaolon tarkistus:
|
||||||
|
new_hash.key?(:defcon) #=> true
|
||||||
|
new_hash.value?(3) #=> true
|
||||||
|
|
||||||
|
# Vinkki! Sekä taulukot että hashit sisältävät Enumerable-moduulin,
|
||||||
|
# johon kuuluu useita hyödyllisiä iterointimetodeja kuten .each, .map,
|
||||||
|
# .reduce ja .count
|
||||||
|
|
||||||
|
# Rakenteita
|
||||||
|
|
||||||
|
if true
|
||||||
|
'if statement'
|
||||||
|
elsif false
|
||||||
|
'else if, optional'
|
||||||
|
else
|
||||||
|
'else, also optional'
|
||||||
|
end
|
||||||
|
|
||||||
|
for counter in 1..5
|
||||||
|
puts "iteration #{counter}"
|
||||||
|
end
|
||||||
|
#=> iteration 1
|
||||||
|
#=> iteration 2
|
||||||
|
#=> iteration 3
|
||||||
|
#=> iteration 4
|
||||||
|
#=> iteration 5
|
||||||
|
|
||||||
|
# HUOMAA, että for-rakennetta kannattaa välttää, sillä Rubyssa suosittu
|
||||||
|
# each-metodi ajaa saman asian idiomaattisemmin. Each-metodi ottaa ainoana
|
||||||
|
# argumenttinaan lohkon. Lohkot toimivat pitkälti samoin kuin muiden kielten
|
||||||
|
# anonyymit funktiot, lambdat tai sulkeumat.
|
||||||
|
|
||||||
|
# Lukuvälit vastaavat each-metodiin, jolloin sille annettu lohko ajetaan
|
||||||
|
# kerran jokaiselle välin kokonaisluvulle.
|
||||||
|
# Lukuvälin each-rakenne lohkoineen näyttää tältä:
|
||||||
|
|
||||||
|
(1..5).each do |counter|
|
||||||
|
puts "iteration #{counter}"
|
||||||
|
end
|
||||||
|
#=> iteration 1
|
||||||
|
#=> iteration 2
|
||||||
|
#=> iteration 3
|
||||||
|
#=> iteration 4
|
||||||
|
#=> iteration 5
|
||||||
|
|
||||||
|
# Lohkoa ympäröivät do/end-avainsanat voi korvata myös aaltosulkeilla:
|
||||||
|
(1..5).each { |counter| puts "iteration #{counter}" }
|
||||||
|
|
||||||
|
# Lukuvälien lisäksi myös tietorakenteita voidaan iteroida each-metodilla:
|
||||||
|
array.each do |element|
|
||||||
|
puts "#{element} is part of the array"
|
||||||
|
end
|
||||||
|
hash.each do |key, value|
|
||||||
|
puts "#{key} is #{value}"
|
||||||
|
end
|
||||||
|
|
||||||
|
# Taulukoita voi iteroida metodilla each_with_index, jolloin lohko saa
|
||||||
|
# argumenteikseen sekä alkion että indeksin:
|
||||||
|
array.each_with_index do |element, index|
|
||||||
|
puts "#{element} is number #{index} in the array"
|
||||||
|
end
|
||||||
|
|
||||||
|
counter = 1
|
||||||
|
while counter <= 5 do
|
||||||
|
puts "iteration #{counter}"
|
||||||
|
counter += 1
|
||||||
|
end
|
||||||
|
#=> iteration 1
|
||||||
|
#=> iteration 2
|
||||||
|
#=> iteration 3
|
||||||
|
#=> iteration 4
|
||||||
|
#=> iteration 5
|
||||||
|
|
||||||
|
# Each-metodin lisäksi Rubyssa on useita muita iterointimetodeja kuten
|
||||||
|
# "map" ja "reduce". Näistä "map" kutsuttuna taulukolla ottaa argumentikseen
|
||||||
|
# lohkon, suorittaa sen kerran jokaiselle rakenteen jäsenelle, ja lopuksi
|
||||||
|
# palauttaa uuden taulukon, jonka jäsenet ovat lohkon suorituksen tuloksia.
|
||||||
|
|
||||||
|
array = [1, 2, 3, 4, 5]
|
||||||
|
doubled = array.map do |element|
|
||||||
|
element * 2
|
||||||
|
end
|
||||||
|
puts doubled
|
||||||
|
#=> [2,4,6,8,10]
|
||||||
|
puts array
|
||||||
|
#=> [1,2,3,4,5]
|
||||||
|
|
||||||
|
# Case-rakenne siirtää ohjelman kulun yhdelle monista määritellyistä poluista:
|
||||||
|
|
||||||
|
grade = 'B'
|
||||||
|
|
||||||
|
case grade
|
||||||
|
when 'A'
|
||||||
|
puts 'Way to go kiddo'
|
||||||
|
when 'B'
|
||||||
|
puts 'Better luck next time'
|
||||||
|
when 'C'
|
||||||
|
puts 'You can do better'
|
||||||
|
when 'D'
|
||||||
|
puts 'Scraping through'
|
||||||
|
when 'F'
|
||||||
|
puts 'You failed!'
|
||||||
|
else
|
||||||
|
puts 'Alternative grading system, eh?'
|
||||||
|
end
|
||||||
|
#=> "Better luck next time"
|
||||||
|
|
||||||
|
# Case-rakenteessa voidaan hyödyntää lukuvälejä:
|
||||||
|
grade = 82
|
||||||
|
case grade
|
||||||
|
when 90..100
|
||||||
|
puts 'Hooray!'
|
||||||
|
when 80...90
|
||||||
|
puts 'OK job'
|
||||||
|
else
|
||||||
|
puts 'You failed!'
|
||||||
|
end
|
||||||
|
#=> "OK job"
|
||||||
|
|
||||||
|
# Virheidenkäsittely:
|
||||||
|
begin
|
||||||
|
# Seuraava koodinpätkä aiheuttaa NoMemoryError-poikkeuksen
|
||||||
|
raise NoMemoryError, 'You ran out of memory.'
|
||||||
|
rescue NoMemoryError => exception_variable
|
||||||
|
puts 'NoMemoryError was raised', exception_variable
|
||||||
|
rescue RuntimeError => other_exception_variable
|
||||||
|
puts 'RuntimeError was raised now'
|
||||||
|
else
|
||||||
|
puts 'This runs if no exceptions were thrown at all'
|
||||||
|
ensure
|
||||||
|
puts 'This code always runs no matter what'
|
||||||
|
end
|
||||||
|
|
||||||
|
# Ylimmän näkyvyysalueen metodi näyttää itsenäiseltä funktiolta:
|
||||||
|
def double(x)
|
||||||
|
x * 2
|
||||||
|
end
|
||||||
|
|
||||||
|
# Funktiot (ja lohkot) palauttavat implisiittisesti
|
||||||
|
# viimeiseksi ajamansa lausekkeen arvon:
|
||||||
|
double(2) #=> 4
|
||||||
|
|
||||||
|
# Metodikutsun argumentteja ympäröivät kaarisulkeet voi jättää pois,
|
||||||
|
# kunhan koodi ei muutu monitulkintaiseksi:
|
||||||
|
|
||||||
|
double 3 #=> 6
|
||||||
|
|
||||||
|
double double 3 #=> 12
|
||||||
|
|
||||||
|
def sum(x, y)
|
||||||
|
x + y
|
||||||
|
end
|
||||||
|
|
||||||
|
# Argumentit erotetaan pilkuilla:
|
||||||
|
|
||||||
|
sum 3, 4 #=> 7
|
||||||
|
|
||||||
|
sum sum(3, 4), 5 #=> 12
|
||||||
|
|
||||||
|
# Kaikilla metodeilla on implisiittinen lohkoparametri,
|
||||||
|
# joka voidaan suorittaa yield-avainsanalla:
|
||||||
|
|
||||||
|
def surround
|
||||||
|
puts '{'
|
||||||
|
yield
|
||||||
|
puts '}'
|
||||||
|
end
|
||||||
|
|
||||||
|
surround { puts 'hello world' }
|
||||||
|
|
||||||
|
# {
|
||||||
|
# hello world
|
||||||
|
# }
|
||||||
|
|
||||||
|
# Metodille annetun lohkon voi nimetä parametrilistassa &-merkin avulla,
|
||||||
|
# minkä jälkeen se suoritetaan call-metodilla:
|
||||||
|
def guests(&block)
|
||||||
|
block.call 'some_argument'
|
||||||
|
end
|
||||||
|
|
||||||
|
# Metodille voi antaa vaihtelevan määrän muuttujia. Ne siirretään taulukkoon,
|
||||||
|
# jolle annetaan parametrilistassa nimi \*-merkin avulla
|
||||||
|
def guests(*array)
|
||||||
|
array.each { |guest| puts guest }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Luokan määritys aloitetaan class-avainsanalla:
|
||||||
|
|
||||||
|
class Human
|
||||||
|
|
||||||
|
# Tässä luokkamuuttuja, joka on yhteinen kaikille luokan olioille:
|
||||||
|
@@species = 'H. sapiens'
|
||||||
|
|
||||||
|
# Alustusmetodin määrittely:
|
||||||
|
def initialize(name, age = 0)
|
||||||
|
# name-oliomuuttujan arvon asetus metodille annetun name-muuttujan mukaan:
|
||||||
|
@name = name
|
||||||
|
|
||||||
|
# Jos tätä metodia kutsuessa jätetään toinen argumentti (age) antamatta,
|
||||||
|
# saa se parametriluettelossa määritetyn arvon 0:
|
||||||
|
@age = age
|
||||||
|
end
|
||||||
|
|
||||||
|
# Tyypillinen oliomuuttujan arvon asettava metodi:
|
||||||
|
def name=(name)
|
||||||
|
@name = name
|
||||||
|
end
|
||||||
|
|
||||||
|
# Tyypillinen oliomuuttujan arvon palauttava metodi:
|
||||||
|
def name
|
||||||
|
@name
|
||||||
|
end
|
||||||
|
|
||||||
|
# Edelliset kaksi metodia voi ilmaista idiomaattisemmin myös näin:
|
||||||
|
attr_accessor :name
|
||||||
|
|
||||||
|
# Lisäksi arvon palauttavan ja asettavan metodin voi määritellä erikseen:
|
||||||
|
attr_reader :name
|
||||||
|
attr_writer :name
|
||||||
|
|
||||||
|
# Luokkametodeissa käytetään avainsanaa self erotuksena oliometodeista.
|
||||||
|
# Luokkametodia voi kutsua vain luokalla itsellään, ei olioilla:
|
||||||
|
def self.say(msg)
|
||||||
|
puts msg
|
||||||
|
end
|
||||||
|
|
||||||
|
def species
|
||||||
|
@@species
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Olion luonti:
|
||||||
|
|
||||||
|
jim = Human.new('Jim Halpert')
|
||||||
|
|
||||||
|
dwight = Human.new('Dwight K. Schrute')
|
||||||
|
|
||||||
|
# Olion metodien kutsuja:
|
||||||
|
jim.species #=> "H. sapiens"
|
||||||
|
jim.name #=> "Jim Halpert"
|
||||||
|
jim.name = "Jim Halpert II" #=> "Jim Halpert II"
|
||||||
|
jim.name #=> "Jim Halpert II"
|
||||||
|
dwight.species #=> "H. sapiens"
|
||||||
|
dwight.name #=> "Dwight K. Schrute"
|
||||||
|
|
||||||
|
# Luokkametodin kutsu:
|
||||||
|
Human.say('Hi') #=> "Hi"
|
||||||
|
|
||||||
|
# Muuttujan näkyvyysalueen voi määritellä etuliitteellä.
|
||||||
|
|
||||||
|
# $-alkuiset muuttujat ovat globaaleja:
|
||||||
|
$var = "I'm a global var"
|
||||||
|
defined? $var #=> "global-variable"
|
||||||
|
|
||||||
|
# @-alkuiset muuttujat kuuluvat oliolle,
|
||||||
|
# jonka näkyvyysalueella määrittely tehdään:
|
||||||
|
@var = "I'm an instance var"
|
||||||
|
defined? @var #=> "instance-variable"
|
||||||
|
|
||||||
|
# @@-alkuiset muuttujat kuuluvat vastaavasti näkyvyysalueensa luokalle:
|
||||||
|
@@var = "I'm a class var"
|
||||||
|
defined? @@var #=> "class variable"
|
||||||
|
|
||||||
|
# Isolla alkukirjaimella nimetyt muuttujat ovatkin vakioita:
|
||||||
|
Var = "I'm a constant"
|
||||||
|
defined? Var #=> "constant"
|
||||||
|
|
||||||
|
# Kuten odottaa saattaa, myös luokat itsessään ovat olioita.
|
||||||
|
# Siksi niille voi määritellä muuttujia, jotka ovat yhteisiä kaikille
|
||||||
|
# luokan ilmentymille ja perillisille.
|
||||||
|
|
||||||
|
# Tavallisen luokan määrittely:
|
||||||
|
|
||||||
|
class Human
|
||||||
|
@@foo = 0
|
||||||
|
|
||||||
|
def self.foo
|
||||||
|
@@foo
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.foo=(value)
|
||||||
|
@@foo = value
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Perillisluokan määrittely:
|
||||||
|
|
||||||
|
class Worker < Human
|
||||||
|
end
|
||||||
|
|
||||||
|
Human.foo # 0
|
||||||
|
Worker.foo # 0
|
||||||
|
|
||||||
|
Human.foo = 2 # 2
|
||||||
|
Worker.foo # 2
|
||||||
|
|
||||||
|
# Oliomuuttuja on kuitenkin olion oma eikä periydy:
|
||||||
|
|
||||||
|
class Human
|
||||||
|
@bar = 0
|
||||||
|
|
||||||
|
def self.bar
|
||||||
|
@bar
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.bar=(value)
|
||||||
|
@bar = value
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class Doctor < Human
|
||||||
|
end
|
||||||
|
|
||||||
|
Human.bar # 0
|
||||||
|
Doctor.bar # nil
|
||||||
|
|
||||||
|
module ModuleExample
|
||||||
|
def foo
|
||||||
|
'foo'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Moduulien lisääminen luokkaan "include"-avainsanalla siirtää moduulin metodit
|
||||||
|
# luokan ilmentymille, kun taas "extend" avainsana siirtää metodit
|
||||||
|
# luokalle itselleen:
|
||||||
|
|
||||||
|
class Person
|
||||||
|
include ModuleExample
|
||||||
|
end
|
||||||
|
|
||||||
|
class Book
|
||||||
|
extend ModuleExample
|
||||||
|
end
|
||||||
|
|
||||||
|
Person.foo # => NoMethodError: undefined method `foo' for Person:Class
|
||||||
|
Person.new.foo # => 'foo'
|
||||||
|
Book.foo # => 'foo'
|
||||||
|
Book.new.foo # => NoMethodError: undefined method `foo'
|
||||||
|
|
||||||
|
# Callback-tyyppiset metodit suoritetaan moduulia sisällyttäessä:
|
||||||
|
|
||||||
|
module ConcernExample
|
||||||
|
def self.included(base)
|
||||||
|
base.extend(ClassMethods)
|
||||||
|
base.send(:include, InstanceMethods)
|
||||||
|
end
|
||||||
|
|
||||||
|
module ClassMethods
|
||||||
|
def bar
|
||||||
|
'bar'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
module InstanceMethods
|
||||||
|
def qux
|
||||||
|
'qux'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class Something
|
||||||
|
include ConcernExample
|
||||||
|
end
|
||||||
|
|
||||||
|
Something.bar # => 'bar'
|
||||||
|
Something.qux # => NoMethodError: undefined method `qux'
|
||||||
|
Something.new.bar # => NoMethodError: undefined method `bar'
|
||||||
|
Something.new.qux # => 'qux'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Lisämateriaalia englanniksi
|
||||||
|
|
||||||
|
- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Selaimessa tehtäviä harjoituksia tämän dokumentin hengessä
|
||||||
|
- [An Interactive Tutorial for Ruby](https://rubymonk.com/)
|
||||||
|
- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - Virallinen dokumentaatio
|
||||||
|
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
|
||||||
|
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Vanhempi, mutta [ilmainen painos](http://ruby-doc.com/docs/ProgrammingRuby/) on luettavissa netissä
|
||||||
|
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Yhteisön luoma Ruby-tyyliopas
|
||||||
|
- [Try Ruby](http://tryruby.org) - Rubyn perusteet interaktiivisesti
|
116
fr-fr/HTML-fr.html.markdown
Normal file
116
fr-fr/HTML-fr.html.markdown
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
---
|
||||||
|
language: html
|
||||||
|
filename: learnhtml-fr.html
|
||||||
|
contributors:
|
||||||
|
- ["Christophe THOMAS", "https://github.com/WinChris"]
|
||||||
|
lang: fr-fr
|
||||||
|
---
|
||||||
|
|
||||||
|
HTML signifie HyperText Markup Language.
|
||||||
|
C'est un langage (format de fichiers) qui permet d'écrire des pages internet.
|
||||||
|
C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais).
|
||||||
|
Les fichiers HTML sont en réalité de simple fichier texte.
|
||||||
|
Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante.
|
||||||
|
Ce balisage sert à donner une signification au texte ainsi entouré.
|
||||||
|
Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5.
|
||||||
|
|
||||||
|
**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
|
||||||
|
Cet article porte principalement sur la syntaxe et quelques astuces.
|
||||||
|
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!-- Les commentaires sont entouré comme cette ligne! -->
|
||||||
|
|
||||||
|
<!-- #################### Les balises #################### -->
|
||||||
|
|
||||||
|
<!-- Voici un exemple de fichier HTML que nous allons analyser -->
|
||||||
|
<!-- Venez voir ce que ça donne -->
|
||||||
|
|
||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Mon Site</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Hello, world!</h1>
|
||||||
|
<a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a>
|
||||||
|
<p>Ceci est un paragraphe</p>
|
||||||
|
<p>Ceci est un autre paragraphe</p>
|
||||||
|
<ul>
|
||||||
|
<li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
|
||||||
|
<li>Ceci est un autre item</li>
|
||||||
|
<li>Et ceci est le dernier item de la liste</li>
|
||||||
|
</ul>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
|
<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML -->
|
||||||
|
|
||||||
|
<!doctype html>
|
||||||
|
|
||||||
|
<!-- Après ça on commence par ouvrir une balise <html> -->
|
||||||
|
<html>
|
||||||
|
</html>
|
||||||
|
<!-- Et puis on la referme à la fin du fichier avec </html> -->
|
||||||
|
<!-- après cette balise de fin, plus rien ne doit apparaître. -->
|
||||||
|
|
||||||
|
<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : -->
|
||||||
|
|
||||||
|
<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) -->
|
||||||
|
<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées -->
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre -->
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<!-- Après la balise <head>, on trouve la balise <body> -->
|
||||||
|
<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. -->
|
||||||
|
<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu -->
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre -->
|
||||||
|
<!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) -->
|
||||||
|
<a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" -->
|
||||||
|
<p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html -->
|
||||||
|
<p>Ceci est un autre paragraphe</p>
|
||||||
|
<ul> <!-- La balise <ul> permet d'introduire une liste à puces -->
|
||||||
|
<!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc -->
|
||||||
|
<li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
|
||||||
|
<li>Ceci est un autre item</li>
|
||||||
|
<li>Et ceci est le dernier item de la liste</li>
|
||||||
|
</ul>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
<!-- Voilà comment créer un fichier HTML simple -->
|
||||||
|
|
||||||
|
<!-- Mais il est possible d'ajouter encore des balises plus spécifiques -->
|
||||||
|
|
||||||
|
<!-- Pour insérer une image -->
|
||||||
|
<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" -->
|
||||||
|
<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur -->
|
||||||
|
|
||||||
|
<!-- Il est possible de réaliser des tableaux également -->
|
||||||
|
|
||||||
|
<table> <!-- On ouvre la balise <table> -->
|
||||||
|
<tr> <!-- <tr> permet de créer une ligne -->
|
||||||
|
<th>First Header</th> <!-- <th> permet de créer un titre au tableau -->
|
||||||
|
<th>Second Header</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule -->
|
||||||
|
<td>Première ligne, deuxième cellule</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Deuxième ligne, première cellule</td>
|
||||||
|
<td>Deuxième ligne, deuxième cellule</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
## Utilisation
|
||||||
|
|
||||||
|
Le HTML s'écrit dans des fichiers `.html`.
|
||||||
|
|
||||||
|
## En savoir plus
|
||||||
|
|
||||||
|
* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html)
|
||||||
|
* [W3School](http://www.w3schools.com/html/html_intro.asp)
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
filename: learnbrainfuck-fr.bf
|
filename: learnbrainfuck-fr.bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
@ -8,7 +8,7 @@ translators:
|
|||||||
lang: fr-fr
|
lang: fr-fr
|
||||||
---
|
---
|
||||||
|
|
||||||
Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs,
|
Au début du web, il n'y avait pas d'élements visuels, simplement du texte pur. Mais avec le dévelopement des navigateurs,
|
||||||
des pages avec du contenu visuel sont arrivées.
|
des pages avec du contenu visuel sont arrivées.
|
||||||
CSS est le langage standard qui existe et permet de garder une séparation entre
|
CSS est le langage standard qui existe et permet de garder une séparation entre
|
||||||
le contenu (HTML) et le style d'une page web.
|
le contenu (HTML) et le style d'une page web.
|
||||||
@ -16,8 +16,8 @@ le contenu (HTML) et le style d'une page web.
|
|||||||
En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents
|
En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents
|
||||||
sur une page HTML afin de leur donner des propriétés visuelles différentes.
|
sur une page HTML afin de leur donner des propriétés visuelles différentes.
|
||||||
|
|
||||||
Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0
|
Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parler de CSS2.0
|
||||||
qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur.
|
qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateurs.
|
||||||
|
|
||||||
**NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
|
**NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
|
||||||
Cet article porte principalement sur la syntaxe et quelques astuces.
|
Cet article porte principalement sur la syntaxe et quelques astuces.
|
||||||
@ -33,7 +33,7 @@ Cet article porte principalement sur la syntaxe et quelques astuces.
|
|||||||
/* Généralement, la première déclaration en CSS est très simple */
|
/* Généralement, la première déclaration en CSS est très simple */
|
||||||
selecteur { propriete: valeur; /* autres proprietés...*/ }
|
selecteur { propriete: valeur; /* autres proprietés...*/ }
|
||||||
|
|
||||||
/* Le sélécteur sert à cibler un élément du HTML
|
/* Le sélecteur sert à cibler un élément du HTML
|
||||||
|
|
||||||
Vous pouvez cibler tous les éléments d'une page! */
|
Vous pouvez cibler tous les éléments d'une page! */
|
||||||
* { color:red; }
|
* { color:red; }
|
||||||
|
264
fr-fr/d.html.markdown
Normal file
264
fr-fr/d.html.markdown
Normal file
@ -0,0 +1,264 @@
|
|||||||
|
---
|
||||||
|
language: D
|
||||||
|
filename: learnd-fr.d
|
||||||
|
contributors:
|
||||||
|
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
|
||||||
|
translators:
|
||||||
|
- ["Quentin Ladeveze", "aceawan.eu"]
|
||||||
|
lang: fr-fr
|
||||||
|
---
|
||||||
|
|
||||||
|
```c
|
||||||
|
// Commençons par un classique
|
||||||
|
module hello;
|
||||||
|
|
||||||
|
import std.stdio;
|
||||||
|
|
||||||
|
// args n'est pas obligatoire
|
||||||
|
void main(string[] args) {
|
||||||
|
writeln("Bonjour le monde !");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a
|
||||||
|
de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/).
|
||||||
|
D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient
|
||||||
|
des fonctionnalités aussi bien de bas niveau que de haut niveau.
|
||||||
|
|
||||||
|
D est activement développé par de nombreuses personnes très intelligents, guidées par
|
||||||
|
[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et
|
||||||
|
[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu).
|
||||||
|
Après cette petite introduction, jetons un coup d'oeil à quelques exemples.
|
||||||
|
|
||||||
|
```c
|
||||||
|
import std.stdio;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
//Les conditions et les boucles sont classiques.
|
||||||
|
for(int i = 0; i < 10000; i++) {
|
||||||
|
writeln(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// On peut utiliser auto pour inférer automatiquement le
|
||||||
|
// type d'une variable.
|
||||||
|
auto n = 1;
|
||||||
|
|
||||||
|
// On peut faciliter la lecture des valeurs numériques
|
||||||
|
// en y insérant des `_`.
|
||||||
|
while(n < 10_000) {
|
||||||
|
n += n;
|
||||||
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
n -= (n / 2);
|
||||||
|
} while(n > 0);
|
||||||
|
|
||||||
|
// For et while sont très utiles, mais en D, on préfère foreach.
|
||||||
|
// Les deux points : '..', créent un intervalle continue de valeurs
|
||||||
|
// incluant la première mais excluant la dernière.
|
||||||
|
foreach(i; 1..1_000_000) {
|
||||||
|
if(n % 2 == 0)
|
||||||
|
writeln(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// On peut également utiliser foreach_reverse pour itérer à l'envers.
|
||||||
|
foreach_reverse(i; 1..int.max) {
|
||||||
|
if(n % 2 == 1) {
|
||||||
|
writeln(i);
|
||||||
|
} else {
|
||||||
|
writeln("Non !");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
On peut définir de nouveaux types avec les mots-clés `struct`, `class`,
|
||||||
|
`union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés)
|
||||||
|
De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques.
|
||||||
|
|
||||||
|
```c
|
||||||
|
// Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java.
|
||||||
|
struct LinkedList(T) {
|
||||||
|
T data = null;
|
||||||
|
|
||||||
|
// Utilisez '!' pour instancier un type paramétré.
|
||||||
|
// Encore une fois semblable à '<T>'
|
||||||
|
LinkedList!(T)* next;
|
||||||
|
}
|
||||||
|
|
||||||
|
class BinTree(T) {
|
||||||
|
T data = null;
|
||||||
|
|
||||||
|
// Si il n'y a qu'un seul paramètre de template,
|
||||||
|
// on peut s'abstenir de mettre des parenthèses.
|
||||||
|
BinTree!T left;
|
||||||
|
BinTree!T right;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Day {
|
||||||
|
Sunday,
|
||||||
|
Monday,
|
||||||
|
Tuesday,
|
||||||
|
Wednesday,
|
||||||
|
Thursday,
|
||||||
|
Friday,
|
||||||
|
Saturday,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Utilisez alias pour créer des abreviations pour les types.
|
||||||
|
alias IntList = LinkedList!int;
|
||||||
|
alias NumTree = BinTree!double;
|
||||||
|
|
||||||
|
// On peut tout aussi bien créer des templates de function !
|
||||||
|
T max(T)(T a, T b) {
|
||||||
|
if(a < b)
|
||||||
|
return b;
|
||||||
|
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé
|
||||||
|
// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur.
|
||||||
|
// Ici ils seront toujours passés par référence à 'swap()'.
|
||||||
|
void swap(T)(ref T a, ref T b) {
|
||||||
|
auto temp = a;
|
||||||
|
|
||||||
|
a = b;
|
||||||
|
b = temp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avec les templates, on peut également passer des valeurs en paramètres.
|
||||||
|
class Matrix(uint m, uint n, T = int) {
|
||||||
|
T[m] rows;
|
||||||
|
T[n] columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto mat = new Matrix!(3, 3); // T est 'int' par défaut
|
||||||
|
|
||||||
|
```
|
||||||
|
À propos de classes, parlons des propriétés. Une propriété est, en gros,
|
||||||
|
une méthode qui peut se comporter comme une lvalue. On peut donc utiliser
|
||||||
|
la syntaxe des structures classiques (`struct.x = 7`) comme si il
|
||||||
|
s'agissait de méthodes getter ou setter.
|
||||||
|
|
||||||
|
```c
|
||||||
|
// Considérons une classe paramétrée avec les types 'T' et 'U'
|
||||||
|
class MyClass(T, U) {
|
||||||
|
T _data;
|
||||||
|
U _other;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Et des méthodes "getter" et "setter" comme suit:
|
||||||
|
class MyClass(T, U) {
|
||||||
|
T _data;
|
||||||
|
U _other;
|
||||||
|
|
||||||
|
// Les constructeurs s'apellent toujours 'this'.
|
||||||
|
this(T t, U u) {
|
||||||
|
// Ceci va appeller les setters ci-dessous.
|
||||||
|
data = t;
|
||||||
|
other = u;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters
|
||||||
|
@property T data() {
|
||||||
|
return _data;
|
||||||
|
}
|
||||||
|
|
||||||
|
@property U other() {
|
||||||
|
return _other;
|
||||||
|
}
|
||||||
|
|
||||||
|
// setters
|
||||||
|
@property void data(T t) {
|
||||||
|
_data = t;
|
||||||
|
}
|
||||||
|
|
||||||
|
@property void other(U u) {
|
||||||
|
_other = u;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Et on l'utilise de cette façon:
|
||||||
|
void main() {
|
||||||
|
auto mc = new MyClass!(int, string)(7, "seven");
|
||||||
|
|
||||||
|
// Importer le module 'stdio' de la bibliothèque standard permet
|
||||||
|
// d'écrire dans la console (les imports peuvent être locaux à une portée)
|
||||||
|
import std.stdio;
|
||||||
|
|
||||||
|
// On appelle les getters pour obtenir les valeurs.
|
||||||
|
writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
|
||||||
|
|
||||||
|
// On appelle les setter pour assigner de nouvelles valeurs.
|
||||||
|
mc.data = 8;
|
||||||
|
mc.other = "eight";
|
||||||
|
|
||||||
|
// On appelle les setter pour obtenir les nouvelles valeurs.
|
||||||
|
writefln("Later: data = %d, str = %s", mc.data, mc.other);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Avec les propriétés, on peut constuire nos setters et nos getters
|
||||||
|
comme on le souhaite, tout en gardant un syntaxe très propre,
|
||||||
|
comme si on accédait directement à des membres de la classe.
|
||||||
|
|
||||||
|
Les autres fonctionnalités orientées objets à notre disposition
|
||||||
|
incluent les interfaces, les classes abstraites, et la surcharge
|
||||||
|
de méthodes. D gère l'héritage comme Java: On ne peut hériter que
|
||||||
|
d'une seule classe et implémenter autant d'interface que voulu.
|
||||||
|
|
||||||
|
Nous venons d'explorer les fonctionnalités objet du D, mais changeons
|
||||||
|
un peu de domaine. D permet la programmation fonctionelle, avec les fonctions
|
||||||
|
de premier ordre, les fonctions `pure` et les données immuables.
|
||||||
|
De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter)
|
||||||
|
sont disponibles dans le module `std.algorithm`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
import std.algorithm : map, filter, reduce;
|
||||||
|
import std.range : iota; // construit un intervalle excluant la dernière valeur.
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
// On veut un algorithm qui affiche la somme de la listes des carrés
|
||||||
|
// des entiers paires de 1 à 100. Un jeu d'enfant !
|
||||||
|
|
||||||
|
// On se content de passer des expressions lambda en paramètre à des templates.
|
||||||
|
// On peut fournier au template n'importe quelle fonction, mais dans notre
|
||||||
|
// cas, les lambdas sont pratiques.
|
||||||
|
auto num = iota(1, 101).filter!(x => x % 2 == 0)
|
||||||
|
.map!(y => y ^^ 2)
|
||||||
|
.reduce!((a, b) => a + b);
|
||||||
|
|
||||||
|
writeln(num);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Vous voyez comme on a calculé `num` comme on le ferait en haskell par exemple ?
|
||||||
|
C'est grâce à une innvoation de D qu'on appelle "Uniform Function Call Syntax".
|
||||||
|
Avec l'UFCS, on peut choisir d'écrire un appelle à une fonction de manière
|
||||||
|
classique, ou comme un appelle à une méthode. Walter Brighter a écrit un
|
||||||
|
article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
|
||||||
|
Pour faire court, on peut appeller une fonction dont le premier paramètre
|
||||||
|
est de type A, comme si c'était une méthode de A.
|
||||||
|
|
||||||
|
J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça
|
||||||
|
Voyons comment on le fait en D !
|
||||||
|
|
||||||
|
```c
|
||||||
|
import std.stdio;
|
||||||
|
import std.parallelism : parallel;
|
||||||
|
import std.math : sqrt;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
// On veut calculer la racine carré de tous les nombres
|
||||||
|
// dans notre tableau, et profiter de tous les coeurs
|
||||||
|
// à notre disposition.
|
||||||
|
auto arr = new double[1_000_000];
|
||||||
|
|
||||||
|
// On utilise un index et une référence à chaque élément du tableau.
|
||||||
|
// On appelle juste la fonction parallel sur notre tableau !
|
||||||
|
foreach(i, ref elem; parallel(arr)) {
|
||||||
|
ref = sqrt(i + 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
```
|
@ -3,7 +3,7 @@ name: Go
|
|||||||
category: language
|
category: language
|
||||||
language: Go
|
language: Go
|
||||||
lang: fr-fr
|
lang: fr-fr
|
||||||
filename: learngo.go
|
filename: learngo-fr.go
|
||||||
contributors:
|
contributors:
|
||||||
- ["Sonia Keys", "https://github.com/soniakeys"]
|
- ["Sonia Keys", "https://github.com/soniakeys"]
|
||||||
- ["Christopher Bess", "https://github.com/cbess"]
|
- ["Christopher Bess", "https://github.com/cbess"]
|
||||||
|
180
fr-fr/hy-fr.html.markdown
Normal file
180
fr-fr/hy-fr.html.markdown
Normal file
@ -0,0 +1,180 @@
|
|||||||
|
---
|
||||||
|
language: hy
|
||||||
|
filename: learnhy-fr.hy
|
||||||
|
contributors:
|
||||||
|
- ["Abhishek L", "http://twitter.com/abhishekl"]
|
||||||
|
translators:
|
||||||
|
- ["Hughes Perreault", "https://github.com/hperreault"]
|
||||||
|
lang: fr-fr
|
||||||
|
---
|
||||||
|
|
||||||
|
Hy est un dialecte du lisp bâti par dessus python. Il fonctionne en
|
||||||
|
convertissant le code hy en un arbre de syntaxe abstraite de python (ast).
|
||||||
|
Ceci permet à hy d'appeler du code python et à python d'appeler du code hy.
|
||||||
|
|
||||||
|
Ce tutoriel fonctionne pour hy > 0.9.12
|
||||||
|
|
||||||
|
```clojure
|
||||||
|
;; Ceci est une introduction simple à hy, pour un tutoriel rapide aller à
|
||||||
|
;; http://try-hy.appspot.com
|
||||||
|
;;
|
||||||
|
; Les commentaires se font avec des points-virgules, comme les autres LISPS
|
||||||
|
|
||||||
|
;; les s-expression de bases
|
||||||
|
; Les programmes Lisp sont fait d'expressions symboliques ou sexps qui
|
||||||
|
; ressemblent à
|
||||||
|
(some-function args)
|
||||||
|
; maintenant le quintessentiel hello world
|
||||||
|
(print "hello world")
|
||||||
|
|
||||||
|
;; les types de données simples
|
||||||
|
; Tous les types de données simples sont exactement similaires à leurs
|
||||||
|
; homologues de python
|
||||||
|
42 ; => 42
|
||||||
|
3.14 ; => 3.14
|
||||||
|
True ; => True
|
||||||
|
4+10j ; => (4+10j) un nombre complexe
|
||||||
|
|
||||||
|
; Commençons par un peu d'arithmétique très simple
|
||||||
|
(+ 4 1) ;=> 5
|
||||||
|
; l'opérateur est appliqué à tous les arguments, comme les autres lisps
|
||||||
|
(+ 4 1 2 3) ;=> 10
|
||||||
|
(- 2 1) ;=> 1
|
||||||
|
(* 4 2) ;=> 8
|
||||||
|
(/ 4 1) ;=> 4
|
||||||
|
(% 4 2) ;=> 0 l'opérateur modulo
|
||||||
|
; l'opérateur d'élévation à la puissance est représenté par ** comme en python
|
||||||
|
(** 3 2) ;=> 9
|
||||||
|
; les expressions imbriquées vont se comporter comme on s'y attend
|
||||||
|
(+ 2 (* 4 2)) ;=> 10
|
||||||
|
; aussi, les opérateurs logiques and or not et equal to etc. vont se comporter
|
||||||
|
; comme on s'y attend
|
||||||
|
(= 5 4) ;=> False
|
||||||
|
(not (= 5 4)) ;=> True
|
||||||
|
|
||||||
|
;; variables
|
||||||
|
; les variables sont déclarées en utilisant setv, les noms de variables
|
||||||
|
; peuvent utiliser l'UTF-8 à l'exception de ()[]{}",'`;#|
|
||||||
|
(setv a 42)
|
||||||
|
(setv π 3.14159)
|
||||||
|
(def *foo* 42)
|
||||||
|
;; d'autres types de conteneurs
|
||||||
|
; les chaînes, les listes, les tuples et dicts
|
||||||
|
; ce sont exactement les mêmes que les types de conteneurs de python
|
||||||
|
"hello world" ;=> "hello world"
|
||||||
|
; les opérations sur les chaînes fonctionnent comme en python
|
||||||
|
(+ "hello " "world") ;=> "hello world"
|
||||||
|
; les listes sont créés en utilisant [], l'indexation commence à 0
|
||||||
|
(setv mylist [1 2 3 4])
|
||||||
|
; les tuples sont des structures de données immuables
|
||||||
|
(setv mytuple (, 1 2))
|
||||||
|
; les dictionnaires sont des paires clé-valeur
|
||||||
|
(setv dict1 {"key1" 42 "key2" 21})
|
||||||
|
; :nom peut être utilisé pour définir des mots clés dans hy qui peuvent être
|
||||||
|
; utilisées comme clés
|
||||||
|
(setv dict2 {:key1 41 :key2 20})
|
||||||
|
; utilisez `get' pour obtenir l'élément à l'index / clé
|
||||||
|
(get mylist 1) ;=> 2
|
||||||
|
(get dict1 "key1") ;=> 42
|
||||||
|
; Alternativement, si des mots clés ont été utilisés, l'élément peut être
|
||||||
|
; obtenu directement
|
||||||
|
(:key1 dict2) ;=> 41
|
||||||
|
|
||||||
|
;; fonctions et autres constructions de programme
|
||||||
|
; les fonctions sont définies en utilisant defn, la dernière sexp est renvoyé par défaut
|
||||||
|
(defn greet [name]
|
||||||
|
"A simple greeting" ; une docstring optionnelle
|
||||||
|
(print "hello " name))
|
||||||
|
|
||||||
|
(greet "bilbo") ;=> "hello bilbo"
|
||||||
|
|
||||||
|
; les fonctions peuvent prendre des arguments optionnels ainsi que des
|
||||||
|
; arguments sous forme de mots clés
|
||||||
|
(defn foolists [arg1 &optional [arg2 2]]
|
||||||
|
[arg1 arg2])
|
||||||
|
|
||||||
|
(foolists 3) ;=> [3 2]
|
||||||
|
(foolists 10 3) ;=> [10 3]
|
||||||
|
|
||||||
|
; les fonctions anonymes sont créés en utilisant `fn' ou `lambda'
|
||||||
|
; qui sont semblable à `defn '
|
||||||
|
(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
|
||||||
|
|
||||||
|
;; Opérations sur les séquences
|
||||||
|
; hy a des utilitaires natifs pour les opérations sur les séquences etc.
|
||||||
|
; récupérez le premier élément en utilisant `first' ou `car'
|
||||||
|
(setv mylist [1 2 3 4])
|
||||||
|
(setv mydict {"a" 1 "b" 2})
|
||||||
|
(first mylist) ;=> 1
|
||||||
|
|
||||||
|
; découpez les listes en utilisant slice
|
||||||
|
(slice mylist 1 3) ;=> [2 3]
|
||||||
|
|
||||||
|
; obtenez les éléments d'une liste ou dict en utilisant `get'
|
||||||
|
(get mylist 1) ;=> 2
|
||||||
|
(get mydict "b") ;=> 2
|
||||||
|
; l'indexation des listes commence à 0 comme en python
|
||||||
|
; assoc peut définir les éléments à clés/index
|
||||||
|
(assoc mylist 2 10) ; makes mylist [1 2 10 4]
|
||||||
|
(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3}
|
||||||
|
; il ya tout un tas d'autres fonctions de base qui rend le travail avec
|
||||||
|
; les séquences amusant
|
||||||
|
|
||||||
|
;; les importations fonctionnent comme en pyhtonn
|
||||||
|
(import datetime)
|
||||||
|
(import [functools [partial reduce]]) ; importe fun1 et fun2 de module1
|
||||||
|
(import [matplotlib.pyplot :as plt]) ; faire une importation foo comme bar
|
||||||
|
; toutes les méthodes natives de python sont accessibles à partir de hy
|
||||||
|
; a.foo(arg) est appelé (.foo a arg)
|
||||||
|
(.split (.strip "hello world ")) ;=> ["hello" "world"]
|
||||||
|
|
||||||
|
;; Conditionelles
|
||||||
|
; (if condition (body-if-true) (body-if-false)
|
||||||
|
(if (= passcode "moria")
|
||||||
|
(print "welcome")
|
||||||
|
(print "Speak friend, and Enter!"))
|
||||||
|
|
||||||
|
; imbriquez plusieurs if else if avec le mot clé cond
|
||||||
|
(cond
|
||||||
|
[(= someval 42)
|
||||||
|
(print "Life, universe and everything else!")]
|
||||||
|
[(> someval 42)
|
||||||
|
(print "val too large")]
|
||||||
|
[(< someval 42)
|
||||||
|
(print "val too small")])
|
||||||
|
|
||||||
|
; groupez les expressions avec do, ceux-ci seront executé séquentiellemnt
|
||||||
|
; les expressions comme defn ont un do implicite
|
||||||
|
(do
|
||||||
|
(setv someval 10)
|
||||||
|
(print "someval is set to " someval)) ;=> 10
|
||||||
|
|
||||||
|
; créer une liaison lexicale avec `let', toutes les variables déclarées
|
||||||
|
; comme cela ont une portée locale
|
||||||
|
(let [[nemesis {"superman" "lex luther"
|
||||||
|
"sherlock" "moriarty"
|
||||||
|
"seinfeld" "newman"}]]
|
||||||
|
(for [(, h v) (.items nemesis)]
|
||||||
|
(print (.format "{0}'s nemesis was {1}" h v))))
|
||||||
|
|
||||||
|
;; classes
|
||||||
|
; les classes sont définies comme ceci
|
||||||
|
(defclass Wizard [object]
|
||||||
|
[[--init-- (fn [self spell]
|
||||||
|
(setv self.spell spell) ; init the spell attr
|
||||||
|
None)]
|
||||||
|
[get-spell (fn [self]
|
||||||
|
self.spell)]])
|
||||||
|
|
||||||
|
;; allez voir hylang.org
|
||||||
|
```
|
||||||
|
|
||||||
|
### Lectures complémentaires
|
||||||
|
|
||||||
|
Ce tutoriel est juste une simple introduction à hy/lisp/python.
|
||||||
|
|
||||||
|
La documentation de HY: [http://hy.readthedocs.org](http://hy.readthedocs.org)
|
||||||
|
|
||||||
|
Le repo GitHub de HY: [http://github.com/hylang/hy](http://github.com/hylang/hy)
|
||||||
|
|
||||||
|
Sur freenode irc #hy, twitter hashtag #hylang
|
@ -6,23 +6,26 @@ contributors:
|
|||||||
filename: javascript-fr.js
|
filename: javascript-fr.js
|
||||||
translators:
|
translators:
|
||||||
- ['@nbrugneaux', 'https://nicolasbrugneaux.me']
|
- ['@nbrugneaux', 'https://nicolasbrugneaux.me']
|
||||||
|
- ['Michel Antoine', 'https://github.com/antoin-m']
|
||||||
lang: fr-fr
|
lang: fr-fr
|
||||||
---
|
---
|
||||||
|
|
||||||
JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995.
|
JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995.
|
||||||
Le langage avait à l'origine pour but d'être un langage de scripting simple
|
Le langage avait à l'origine pour but d'être un langage de scripting simple
|
||||||
pour les sites web, complétant le Java (à ne pas confondre avec JavaScript)
|
pour les sites web, complétant le Java (à ne pas confondre avec JavaScript)
|
||||||
pour des applications web complexes. Mais son intégration très proche et
|
pour des applications web complexes. Mais son intégration très proche et
|
||||||
simple des pages web, ainsi que le support natif des navigateurs a rendu
|
simple des pages web, ainsi que le support natif des navigateurs a rendu
|
||||||
le JavaScript incontournable aujourd'hui tant bien dans le front-end que
|
le JavaScript incontournable aujourd'hui tant bien dans le front-end que
|
||||||
dans le back-end.
|
dans le back-end.
|
||||||
|
|
||||||
En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à
|
En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à
|
||||||
Node.JS, un projet qui offre un environnement indépendant dans lequel un
|
Node.JS, un projet qui offre un environnement indépendant dans lequel un
|
||||||
interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
|
interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
|
||||||
peut être utilisé directement côté serveur pour exécuter des programmes écrits
|
peut être utilisé directement côté serveur pour exécuter des programmes écrits
|
||||||
en JavaScript.
|
en JavaScript.
|
||||||
|
|
||||||
|
ECMAScript (la norme du langage Javascript) entre en version 6. Cette version introduit de nombreuses mises à jour tout en restant rétrocompatible. L'implémentation de ces nouvelles fonctionnalités est en cours et celles-ci ne sont donc pas forcément compatibles avec tous les navigateurs.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs,
|
// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs,
|
||||||
/* et les commentaires sur plusieurs lignes commencent avec slash-étoile
|
/* et les commentaires sur plusieurs lignes commencent avec slash-étoile
|
||||||
@ -31,7 +34,7 @@ en JavaScript.
|
|||||||
// Toutes les expressions peuvent finir par ;
|
// Toutes les expressions peuvent finir par ;
|
||||||
doStuff();
|
doStuff();
|
||||||
|
|
||||||
// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
|
// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
|
||||||
// lors de l’interprétation aux sauts de ligne, sauf exceptions
|
// lors de l’interprétation aux sauts de ligne, sauf exceptions
|
||||||
doStuff()
|
doStuff()
|
||||||
|
|
||||||
@ -79,6 +82,12 @@ false; // faux
|
|||||||
"abc";
|
"abc";
|
||||||
'Hello, world';
|
'Hello, world';
|
||||||
|
|
||||||
|
// *ES6:* Les chaines de caractères peuvent être crées en utilisant un modèle
|
||||||
|
// entouré des quotes inverses (`) à la place des quotes classiques (' ou ").
|
||||||
|
// Les variables sont interprétées avec ${var}
|
||||||
|
let banta = "Harry", santa = "Hermione";
|
||||||
|
`${banta}, your santa is ${santa}.` // = "Harry, your santa is Hermione."
|
||||||
|
|
||||||
// La négation utilise le symbole !
|
// La négation utilise le symbole !
|
||||||
!true; // = false
|
!true; // = false
|
||||||
!false; // = true
|
!false; // = true
|
||||||
@ -117,26 +126,34 @@ false; // faux
|
|||||||
|
|
||||||
// Il y a également null et undefined
|
// Il y a également null et undefined
|
||||||
null; // utilisé pour une non-valeur
|
null; // utilisé pour une non-valeur
|
||||||
undefined; // utilisé pour une valeur actuellement non présente (cependant,
|
undefined; // utilisé pour une valeur actuellement non présente (cependant,
|
||||||
// undefined est aussi une valeur valide)
|
// undefined est aussi une valeur valide)
|
||||||
|
|
||||||
// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste
|
// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste
|
||||||
// est 'presque-vrai' (truthy)
|
// est 'presque-vrai' (truthy)
|
||||||
// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0')
|
// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0')
|
||||||
|
|
||||||
|
// *ES6:* Introduction d'un nouveau type primitif : Symbol
|
||||||
|
var symbol_one = Symbol();
|
||||||
|
var symbol_two = Symbol('This is optional description, for debugging');
|
||||||
|
typeof symbol_one === 'symbol' // = true
|
||||||
|
|
||||||
|
// *ES6:* Un Symbol est immutable et unique
|
||||||
|
Symbol() === Symbol() // = false
|
||||||
|
Symbol('learnx') === Symbol('learnx') // = false
|
||||||
|
|
||||||
///////////////////////////////////
|
///////////////////////////////////
|
||||||
// 2. Variables, Tableaux et Objets
|
// 2. Variables, Tableaux, Objets, Maps et Sets
|
||||||
|
|
||||||
// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
|
// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
|
||||||
// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =.
|
// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =.
|
||||||
var someVar = 5;
|
var someVar = 5;
|
||||||
|
|
||||||
// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict)
|
// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict)
|
||||||
someOtherVar = 10;
|
someOtherVar = 10;
|
||||||
|
|
||||||
// ... mais la variable aura une portée globale (plus communément trouvé en tant
|
// ... mais la variable aura une portée globale (plus communément trouvé en tant
|
||||||
// que "global scope" en anglais), et non pas une portée limitée à la fonction
|
// que "global scope" en anglais), et non pas une portée limitée à la fonction
|
||||||
// dans laquelle vous l'aviez définie.
|
// dans laquelle vous l'aviez définie.
|
||||||
|
|
||||||
// Les variables déclarées et non assignées sont undefined par défaut
|
// Les variables déclarées et non assignées sont undefined par défaut
|
||||||
@ -145,6 +162,32 @@ var someThirdVar = undefined;
|
|||||||
|
|
||||||
// ... sont deux déclarations identiques.
|
// ... sont deux déclarations identiques.
|
||||||
|
|
||||||
|
// Il est possible de déclarer plusieurs variables en séparant leur déclaration
|
||||||
|
// avec l'opérateur virgule
|
||||||
|
var someFourthVar = 2, someFifthVar = 4;
|
||||||
|
|
||||||
|
// *ES6:* Les variables peuvent maintenant être déclarées avec les mots-clés
|
||||||
|
// `let` et `const`
|
||||||
|
let someSixthVar = 6;
|
||||||
|
const someSeventhVar = 7;
|
||||||
|
|
||||||
|
// *ES6:* Le mot-clé `let` attache la variable au block de code et non à la fonction
|
||||||
|
// à l'inverse de `var`
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
x += 10;
|
||||||
|
}
|
||||||
|
i; // = raises ReferenceError
|
||||||
|
|
||||||
|
// *ES6:* Les variables "const" doivent être assignées lors de l'initialisation
|
||||||
|
const someEighthVar = 7;
|
||||||
|
const someNinthVar; // raises SyntaxError
|
||||||
|
|
||||||
|
// *ES6:* Modifier une variable constante ne lève par d'erreur mais échoue
|
||||||
|
// silencieusement
|
||||||
|
const someNinthVar = 9;
|
||||||
|
someNinthVar = 10;
|
||||||
|
someNinthVar; // = 9
|
||||||
|
|
||||||
// Il y a des raccourcis pour les opérations mathématiques:
|
// Il y a des raccourcis pour les opérations mathématiques:
|
||||||
someVar += 5; // équivalent pour someVar = someVar + 5;
|
someVar += 5; // équivalent pour someVar = someVar + 5;
|
||||||
someVar *= 10; // de même, someVar = someVar * 100;
|
someVar *= 10; // de même, someVar = someVar * 100;
|
||||||
@ -165,6 +208,22 @@ myArray.length; // = 4
|
|||||||
// Ajout/Modification à un index spécifique
|
// Ajout/Modification à un index spécifique
|
||||||
myArray[3] = 'Hello';
|
myArray[3] = 'Hello';
|
||||||
|
|
||||||
|
// *ES6:* Les Arrays peuvent maintenant être déstructurés en utilisant le pattern matching
|
||||||
|
var [a, b] = [1, 2];
|
||||||
|
var [a, , b] = [1, -2, 2]
|
||||||
|
|
||||||
|
a; // = 1
|
||||||
|
b; // = 2
|
||||||
|
|
||||||
|
// *ES6:* La déstructuration peut échouer silencieusement.
|
||||||
|
// Il est aussi possible d'utiliser des valeurs par défaut
|
||||||
|
var [a] = [];
|
||||||
|
a; // = undefined;
|
||||||
|
var [a = 1] = [];
|
||||||
|
a; // = 1;
|
||||||
|
var [a = 1] = [2];
|
||||||
|
a; // = 2;
|
||||||
|
|
||||||
// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres
|
// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres
|
||||||
// langages : ils sont une liste non-ordonnée de paires clé-valeur.
|
// langages : ils sont une liste non-ordonnée de paires clé-valeur.
|
||||||
var myObj = {key1: 'Hello', key2: 'World'};
|
var myObj = {key1: 'Hello', key2: 'World'};
|
||||||
@ -179,12 +238,55 @@ myObj['my other key']; // = 4
|
|||||||
// .. ou avec un point si la clé est un identifiant valide.
|
// .. ou avec un point si la clé est un identifiant valide.
|
||||||
myObj.myKey; // = 'myValue'
|
myObj.myKey; // = 'myValue'
|
||||||
|
|
||||||
|
// *ES6:* Un Symbol peut être utilisé en tant que clé. Puisque ceux-ci sont uniques,
|
||||||
|
// le seul moyen d'accéder à la propriété est d'avoir une référence sur ce Symbol.
|
||||||
|
myObj["key"] = "public value";
|
||||||
|
myObj[Symbol("key")] = "secret value";
|
||||||
|
myObj[Symbol("key")]; // = undefined
|
||||||
|
|
||||||
// Les objets sont eux aussi modifiables.
|
// Les objets sont eux aussi modifiables.
|
||||||
myObj.myThirdKey = true;
|
myObj.myThirdKey = true;
|
||||||
|
|
||||||
// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined
|
// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined
|
||||||
myObj.myFourthKey; // = undefined
|
myObj.myFourthKey; // = undefined
|
||||||
|
|
||||||
|
// *ES6:* Comme les Arrays, les Objects peuvent être déstructurés en utilisant le pattern matching
|
||||||
|
var {foo} = {foo: "bar"};
|
||||||
|
foo // = "bar"
|
||||||
|
|
||||||
|
// *ES6:* Les Objects déstructurés peuvent utiliser des noms de variables différents
|
||||||
|
// de ceux d'origine grâce au pattern matching
|
||||||
|
var {foo, moo: baz} = {foo: "bar", moo: "car"};
|
||||||
|
foo // = "bar"
|
||||||
|
baz // = "car"
|
||||||
|
|
||||||
|
// *ES6:* Il est possible d'utiliser des valeurs par défaut lor de la déstructuration d'un Object
|
||||||
|
var {foo="bar"} = {moo: "car"};
|
||||||
|
foo // = "bar"
|
||||||
|
|
||||||
|
// *ES6:* Une erreur lors de la déstructuration restera silencieuse
|
||||||
|
var {foo} = {};
|
||||||
|
foo // = undefined
|
||||||
|
|
||||||
|
// *ES6:* Les Maps sont des objets itérables de type clé-valeur.
|
||||||
|
// Il est possible de créer une nouvelle map en utilisant `new Map()`
|
||||||
|
var myMap = new Map();
|
||||||
|
|
||||||
|
// *ES6:* Il est possible d'ajouter un couple clé-valeur avec la méthode `.set()`,
|
||||||
|
// de récupérer une valeur avec `.get()`,
|
||||||
|
// de vérifier qu'une clé existe avec `.has()`
|
||||||
|
// et enfin de supprimer un couple clé-valeur avec `.delete()`
|
||||||
|
|
||||||
|
myMap.set("name", "Douglas");
|
||||||
|
myMap.get("name"); // = "Douglas"
|
||||||
|
myMap.has("name"); // = true
|
||||||
|
myMap.delete("name");
|
||||||
|
|
||||||
|
// *ES6:* Les Sets sont des ensembles de valeurs uniques.
|
||||||
|
// Il est possible de créer un set avec `new Set()`.
|
||||||
|
// Toute valeur non unique est ignorée.
|
||||||
|
var mySet = new Set([1,2,2]);
|
||||||
|
console.log([...mySet]); // = [1,2]
|
||||||
|
|
||||||
///////////////////////////////////
|
///////////////////////////////////
|
||||||
// 3. Logique et structures de contrôle
|
// 3. Logique et structures de contrôle
|
||||||
@ -198,7 +300,7 @@ else if (count === 4) {
|
|||||||
// uniquement quand count est 4
|
// uniquement quand count est 4
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// le reste du temps, si ni 3, ni 4.
|
// le reste du temps, si ni 3, ni 4.
|
||||||
}
|
}
|
||||||
|
|
||||||
// De même pour while.
|
// De même pour while.
|
||||||
@ -218,6 +320,22 @@ for (var i = 0; i < 5; i++){
|
|||||||
// sera exécutée 5 fois
|
// sera exécutée 5 fois
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// La boucle for...in permet d'itérer sur les noms des propriétés d'un objet
|
||||||
|
var description = "";
|
||||||
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
|
for (var x in person){
|
||||||
|
description += person[x] + " ";
|
||||||
|
}
|
||||||
|
description; // = "Paul Ken 18 "
|
||||||
|
|
||||||
|
// *ES6:* La boucle for...of permet d'itérer sur les propriétés d'un objet
|
||||||
|
var description = "";
|
||||||
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
|
for (var x of person){
|
||||||
|
description += x + " ";
|
||||||
|
}
|
||||||
|
description; // = "Paul Ken 18 "
|
||||||
|
|
||||||
// && est le "et" logique, || est le "ou" logique
|
// && est le "et" logique, || est le "ou" logique
|
||||||
if (house.size === 'big' && house.colour === 'blue'){
|
if (house.size === 'big' && house.colour === 'blue'){
|
||||||
house.contains = 'bear';
|
house.contains = 'bear';
|
||||||
@ -264,7 +382,21 @@ function myFunction(thing){
|
|||||||
}
|
}
|
||||||
myFunction('foo'); // = 'FOO'
|
myFunction('foo'); // = 'FOO'
|
||||||
|
|
||||||
// Les fonctions JavaScript sont des objets de première classe, donc peuvent
|
// Attention, la valeur à retourner doit se trouver sur la même ligne que
|
||||||
|
// le mot-clé `return` sinon la fonction retournera systématiquement `undefined`
|
||||||
|
function myFunction(){
|
||||||
|
return // <- semicolon automatically inserted here
|
||||||
|
{thisIsAn: 'object literal'}
|
||||||
|
}
|
||||||
|
myFunction(); // = undefined
|
||||||
|
|
||||||
|
// *ES6:* Les paramètres des fonctions peuvent désormais avoir des valeurs par défaut
|
||||||
|
function default(x, y = 2) {
|
||||||
|
return x + y;
|
||||||
|
}
|
||||||
|
default(10); // == 12
|
||||||
|
|
||||||
|
// Les fonctions JavaScript sont des objets de première classe, donc peuvent
|
||||||
// être réassignées à d'autres variables et passées en tant que paramètres pour
|
// être réassignées à d'autres variables et passées en tant que paramètres pour
|
||||||
// d'autres fonctions
|
// d'autres fonctions
|
||||||
function myFunction(){
|
function myFunction(){
|
||||||
@ -274,13 +406,17 @@ setTimeout(myFunction, 5000);
|
|||||||
// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi
|
// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi
|
||||||
// que Node.js le rendent disponible
|
// que Node.js le rendent disponible
|
||||||
|
|
||||||
// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
|
// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
|
||||||
// anonymes
|
// anonymes
|
||||||
setTimeout(function(){
|
setTimeout(function(){
|
||||||
// ce code s'exécutera dans 5 secondes
|
// ce code s'exécutera dans 5 secondes
|
||||||
}, 5000);
|
}, 5000);
|
||||||
|
|
||||||
// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
|
// *ES6:* Introduction d'un sucre syntaxique permettant de créer
|
||||||
|
// une fonction anonyme de la forme : `param => returnValue`.
|
||||||
|
setTimeout(() => console.log('5 seconds, are up.'), 5000);
|
||||||
|
|
||||||
|
// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
|
||||||
// les fonctions, et pas dans les autres blocs.
|
// les fonctions, et pas dans les autres blocs.
|
||||||
if (true){
|
if (true){
|
||||||
var i = 5;
|
var i = 5;
|
||||||
@ -293,7 +429,7 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre
|
|||||||
var temporary = 5;
|
var temporary = 5;
|
||||||
// Nous pouvons accéder au scope global en assignant à l'objet global,
|
// Nous pouvons accéder au scope global en assignant à l'objet global,
|
||||||
// qui dans les navigateurs est "window". Il est différent dans Node.js,
|
// qui dans les navigateurs est "window". Il est différent dans Node.js,
|
||||||
// le scope global sera en fait local au module dans lequel vous
|
// le scope global sera en fait local au module dans lequel vous
|
||||||
// vous trouvez. http://nodejs.org/api/globals.html
|
// vous trouvez. http://nodejs.org/api/globals.html
|
||||||
window.permanent = 10;
|
window.permanent = 10;
|
||||||
})();
|
})();
|
||||||
@ -302,8 +438,8 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre
|
|||||||
temporary; // raises ReferenceError
|
temporary; // raises ReferenceError
|
||||||
permanent; // = 10
|
permanent; // = 10
|
||||||
|
|
||||||
// Une des fonctionnalités les plus puissantes de Javascript est le système de
|
// Une des fonctionnalités les plus puissantes de Javascript est le système de
|
||||||
// closures. Si une fonction est définie dans une autre fonction, alors la
|
// closures. Si une fonction est définie dans une autre fonction, alors la
|
||||||
// fonction interne aura accès aux variables de la fonction parente, même si
|
// fonction interne aura accès aux variables de la fonction parente, même si
|
||||||
// celle-ci a déjà finie son exécution.
|
// celle-ci a déjà finie son exécution.
|
||||||
function sayHelloInFiveSeconds(name){
|
function sayHelloInFiveSeconds(name){
|
||||||
@ -318,6 +454,18 @@ function sayHelloInFiveSeconds(name){
|
|||||||
}
|
}
|
||||||
sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec
|
sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec
|
||||||
|
|
||||||
|
// *ES6:* Les paramètres des fonctions appelées avec un tableau en entré
|
||||||
|
// préfixé par `...` vont se peupler avec les éléments du tableau
|
||||||
|
function spread(x, y, z) {
|
||||||
|
return x + y + z;
|
||||||
|
}
|
||||||
|
spread(...[1,2,3]); // == 6
|
||||||
|
|
||||||
|
// *ES6:* Les fonctions peuvent recevoir les paramètres dans un tableau en utilisant l'opérateur `...`
|
||||||
|
function spread(x, y, z) {
|
||||||
|
return x + y + z;
|
||||||
|
}
|
||||||
|
spread(...[1,2,3]); // == 6
|
||||||
|
|
||||||
///////////////////////////////////
|
///////////////////////////////////
|
||||||
// 5. Encore plus à propos des Objets; Constructeurs and Prototypes
|
// 5. Encore plus à propos des Objets; Constructeurs and Prototypes
|
||||||
@ -340,7 +488,7 @@ myObj = {
|
|||||||
};
|
};
|
||||||
myObj.myFunc(); // = 'Hello world!'
|
myObj.myFunc(); // = 'Hello world!'
|
||||||
|
|
||||||
// La valeur de "this" change de par l'endroit où la fonction est appelée, et
|
// La valeur de "this" change de par l'endroit où la fonction est appelée, et
|
||||||
// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle
|
// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle
|
||||||
// est appelée hors du contexte l'objet.
|
// est appelée hors du contexte l'objet.
|
||||||
var myFunc = myObj.myFunc;
|
var myFunc = myObj.myFunc;
|
||||||
@ -356,7 +504,7 @@ myObj.myOtherFunc = myOtherFunc;
|
|||||||
myObj.myOtherFunc(); // = 'HELLO WORLD!'
|
myObj.myOtherFunc(); // = 'HELLO WORLD!'
|
||||||
|
|
||||||
// Le contexte correspond à la valeur de "this".
|
// Le contexte correspond à la valeur de "this".
|
||||||
// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
|
// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
|
||||||
// pour une fonction quand elle est appelée grâce à "call" ou "apply".
|
// pour une fonction quand elle est appelée grâce à "call" ou "apply".
|
||||||
var anotherFunc = function(s){
|
var anotherFunc = function(s){
|
||||||
return this.myString + s;
|
return this.myString + s;
|
||||||
@ -371,19 +519,19 @@ Math.min(42, 6, 27); // = 6
|
|||||||
Math.min([42, 6, 27]); // = NaN (uh-oh!)
|
Math.min([42, 6, 27]); // = NaN (uh-oh!)
|
||||||
Math.min.apply(Math, [42, 6, 27]); // = 6
|
Math.min.apply(Math, [42, 6, 27]); // = 6
|
||||||
|
|
||||||
// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
|
// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
|
||||||
// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
|
// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
|
||||||
// "bind" pour garder une référence à la fonction avec ce "this".
|
// "bind" pour garder une référence à la fonction avec ce "this".
|
||||||
var boundFunc = anotherFunc.bind(myObj);
|
var boundFunc = anotherFunc.bind(myObj);
|
||||||
boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!'
|
boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!'
|
||||||
|
|
||||||
// "bind" peut aussi être utilisé pour créer une application partielle de la
|
// "bind" peut aussi être utilisé pour créer une application partielle de la
|
||||||
// fonction (curry)
|
// fonction (curry)
|
||||||
var product = function(a, b){ return a * b; }
|
var product = function(a, b){ return a * b; }
|
||||||
var doubler = product.bind(this, 2);
|
var doubler = product.bind(this, 2);
|
||||||
doubler(8); // = 16
|
doubler(8); // = 16
|
||||||
|
|
||||||
// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
|
// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
|
||||||
// crée et mis à disposition de la fonction via "this". Ces fonctions sont
|
// crée et mis à disposition de la fonction via "this". Ces fonctions sont
|
||||||
// communément appelées constructeurs.
|
// communément appelées constructeurs.
|
||||||
var MyConstructor = function(){
|
var MyConstructor = function(){
|
||||||
@ -395,8 +543,8 @@ myNewObj.myNumber; // = 5
|
|||||||
// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à
|
// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à
|
||||||
// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype.
|
// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype.
|
||||||
|
|
||||||
// Quelques implémentations de JS vous laissent accéder au prototype avec la
|
// Quelques implémentations de JS vous laissent accéder au prototype avec la
|
||||||
// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
|
// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
|
||||||
// et ne fonctionne pas dans certains des navigateurs actuels.
|
// et ne fonctionne pas dans certains des navigateurs actuels.
|
||||||
var myObj = {
|
var myObj = {
|
||||||
myString: 'Hello world!'
|
myString: 'Hello world!'
|
||||||
@ -478,7 +626,7 @@ String.prototype.firstCharacter = function(){
|
|||||||
'abc'.firstCharacter(); // = 'a'
|
'abc'.firstCharacter(); // = 'a'
|
||||||
|
|
||||||
// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles
|
// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles
|
||||||
// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
|
// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
|
||||||
// les vieux navigateurs.
|
// les vieux navigateurs.
|
||||||
|
|
||||||
//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à
|
//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à
|
||||||
@ -492,31 +640,83 @@ if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe
|
|||||||
return new Constructor();
|
return new Constructor();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// *ES6:* Les objets peuvent être équipés de proxies qui permettent d'intercepter
|
||||||
|
// les actions sur leurs propriétés. Voici comment créer un proxy sur un objet :
|
||||||
|
var proxyObject = new Proxy(object, handler);
|
||||||
|
|
||||||
|
// *ES6:* Les méthodes d'un objet handler sont appelées lors de l'interception d'une action.
|
||||||
|
// La méthode `.get()` est appelée à chaque lecture d'une propriété
|
||||||
|
// tandis que la méthode `.set()` est appelée à chaque écriture.
|
||||||
|
var handler = {
|
||||||
|
get (target, key) {
|
||||||
|
console.info('Get on property' + key);
|
||||||
|
return target[key];
|
||||||
|
},
|
||||||
|
set (target, key, value) {
|
||||||
|
console.info('Set on property' + key);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// *ES6:* Les classes peuvent désormais être définies en utilisant le mot-clé `class`.
|
||||||
|
// Le constructeur s'appelle `constructor` et les méthodes statiques utilisent le mot-clé `static`
|
||||||
|
class Foo {
|
||||||
|
constructor() {console.log("constructing Foo");}
|
||||||
|
bar() {return "bar";}
|
||||||
|
static baz() {return "baz";}
|
||||||
|
}
|
||||||
|
|
||||||
|
// *ES6:* Les objets issus des classes sont initialisés avec le mot-clé `new`.
|
||||||
|
// Il est possible d'hériter d'une classe avec le mot-clé `extends`
|
||||||
|
var FooObject = new Foo(); // = "constructing Foo"
|
||||||
|
class Zoo extends Foo {}
|
||||||
|
|
||||||
|
// *ES6:* Les méthodes statiques doivent être appelées par la classe, les autres méthodes par l'objet
|
||||||
|
Foo.baz() // = "baz"
|
||||||
|
FooObject.bar() // = "bar"
|
||||||
|
|
||||||
|
// *ES6:* Il est désormais possible d'exporter des valeurs en tant que module.
|
||||||
|
// Les exports peuvent être n'importe quel objet, valeur ou fonction.
|
||||||
|
var api = {
|
||||||
|
foo: "bar",
|
||||||
|
baz: "ponyfoo"
|
||||||
|
};
|
||||||
|
export default api;
|
||||||
|
|
||||||
|
// *ES6:* La syntaxe `export default` permet d'exporter l'objet sans en changer le nom.
|
||||||
|
// Il y a plusieurs façons de l'importer:
|
||||||
|
import coolapi from "api"; // = importe le module dans la variable `coolapi`
|
||||||
|
import {foo, baz} from "api"; // = importe les attributs `foo` et `baz` du module
|
||||||
|
import {foo as moo, baz} from "api"; // = importe les attributs `foo` (en le renommant `moo`) et `baz` du module
|
||||||
|
import _, {map} from "api"; // = importe les exports par défaut ET `map`
|
||||||
|
import * as coolapi from "api"; // = importe le namespace global du module
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Pour aller plus loin (en anglais)
|
## Pour aller plus loin (en anglais)
|
||||||
|
|
||||||
The [Mozilla Developer
|
The [Mozilla Developer
|
||||||
Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une
|
Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une
|
||||||
excellente documentation pour le Javascript dans les navigateurs. Et contient
|
excellente documentation pour le Javascript dans les navigateurs. Et contient
|
||||||
également un wiki pour s'entraider.
|
également un wiki pour s'entraider.
|
||||||
|
|
||||||
MDN's [A re-introduction to
|
MDN's [A re-introduction to
|
||||||
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
||||||
recouvre les principaux sujets vus ici. Le guide est délibérément uniquement
|
recouvre les principaux sujets vus ici. Le guide est délibérément uniquement
|
||||||
à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
|
à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
|
||||||
plutôt ici :
|
plutôt ici :
|
||||||
[Document Object
|
[Document Object
|
||||||
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
|
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
|
||||||
|
|
||||||
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
|
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
|
||||||
|
|
||||||
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
|
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
|
||||||
un guide pour vous éviter les faux-amis dans le JavaScript.
|
un guide pour vous éviter les faux-amis dans le JavaScript.
|
||||||
|
|
||||||
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
|
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
|
||||||
|
|
||||||
En addition aux contributeurs de cet article, du contenu provient du
|
En addition aux contributeurs de cet article, du contenu provient du
|
||||||
"Python tutorial" de Louie Dinh, et de [JS
|
"Python tutorial" de Louie Dinh, et de [JS
|
||||||
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
||||||
sur le réseau Mozilla.
|
sur le réseau Mozilla.
|
||||||
|
@ -4,7 +4,7 @@ filename: learnLivescript-fr.ls
|
|||||||
contributors:
|
contributors:
|
||||||
- ["Christina Whyte", "http://github.com/kurisuwhyte/"]
|
- ["Christina Whyte", "http://github.com/kurisuwhyte/"]
|
||||||
translators:
|
translators:
|
||||||
- ["Morgan Bohn", "https://github.com/morganbohn"]
|
- ["Morgan Bohn", "https://github.com/dotmobo"]
|
||||||
lang: fr-fr
|
lang: fr-fr
|
||||||
---
|
---
|
||||||
|
|
||||||
|
268
fr-fr/make-fr.html.markdown
Normal file
268
fr-fr/make-fr.html.markdown
Normal file
@ -0,0 +1,268 @@
|
|||||||
|
---
|
||||||
|
language: make
|
||||||
|
contributors:
|
||||||
|
- ["Robert Steed", "https://github.com/robochat"]
|
||||||
|
translators:
|
||||||
|
- ["altaris", "https://github.com/altaris"]
|
||||||
|
filename: Makefile-fr
|
||||||
|
lang: fr-fr
|
||||||
|
---
|
||||||
|
|
||||||
|
Un makefile est un fichier qui définit un ensemble de règles liées entre elles
|
||||||
|
pour créer une ou plusieurs cibles. L'idée est d'effectuer le moins de travail
|
||||||
|
possible afin de mettre à jour la ou les cibles en fonction des dépendances.
|
||||||
|
|
||||||
|
Écrit en un week-end par Stuart Feldman en 1976, le make et les
|
||||||
|
makefiles sont encore très utilisés (principalement dans les systèmes Unix),
|
||||||
|
malgré la concurrence et les critiques faites à son égard.
|
||||||
|
|
||||||
|
Le programme make a plusieurs variantes. Dans ce tutoriel, nous utiliserons
|
||||||
|
l'implémentation standard : GNU make.
|
||||||
|
|
||||||
|
```make
|
||||||
|
|
||||||
|
# Ceci est un commentaire.
|
||||||
|
|
||||||
|
# Un makefile devrait être nommé "Makefile" (avec ou sans la
|
||||||
|
# majuscule). Il peut alors être exécuté par `make <cible>`.
|
||||||
|
# Ce nommage n'est toutefois pas obligatoire : utiliser
|
||||||
|
# `make -f "fichier" <cible>`.
|
||||||
|
|
||||||
|
# ATTENTION : l'indentation est quant à elle obligatoire, et se fait avec des
|
||||||
|
# tabulations, pas avec des espaces !
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Les basiques
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas.
|
||||||
|
fichier0.txt:
|
||||||
|
echo "truc" > fichier0.txt
|
||||||
|
# Même les commentaires sont transférés dans le terminal.
|
||||||
|
|
||||||
|
# Cette règle ne sera exécutée que si fichier0.txt est plus récent que
|
||||||
|
# fichier1.txt.
|
||||||
|
fichier1.txt: fichier0.txt
|
||||||
|
cat fichier0.txt > fichier1.txt
|
||||||
|
# Utiliser la même syntaxe que dans un terminal.
|
||||||
|
@cat fichier0.txt >> fichier1.txt
|
||||||
|
# @ empêche l'affichage de la sortie texte d'une commande.
|
||||||
|
-@echo 'hello'
|
||||||
|
# - signifie que la règle devrait continuer à s'exécuter si cette commande
|
||||||
|
# échoue.
|
||||||
|
|
||||||
|
# Une règle peut avoir plusieurs cibles et plusieurs dépendances.
|
||||||
|
fichier2.txt fichier3.txt: fichier0.txt fichier1.txt
|
||||||
|
touch fichier2.txt
|
||||||
|
touch fichier3.txt
|
||||||
|
|
||||||
|
# Make affichera un avertissement si le makefile comporte plusieurs règles pour
|
||||||
|
# une même cible. Cependant les règles vides ne comptent pas, et peuvent être
|
||||||
|
# utilisées pour ajouter des dépendances plus facilement.
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Fausses règles
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Une fausse règle est une règle qui ne correspond pas à un fichier.
|
||||||
|
# Par définition, elle ne peut pas être à jour, et donc make l’exécutera à
|
||||||
|
# chaque demande.
|
||||||
|
all: maker process
|
||||||
|
|
||||||
|
# La déclaration des règles peut être faite dans n'importe quel ordre.
|
||||||
|
maker:
|
||||||
|
touch ex0.txt ex1.txt
|
||||||
|
|
||||||
|
# On peut transformer une règle en fausse règle grâce à la cible spéciale
|
||||||
|
# suivante :
|
||||||
|
.PHONY: all maker process
|
||||||
|
|
||||||
|
# Une règle dépendante d'une fausse règle sera toujours exécutée.
|
||||||
|
ex0.txt ex1.txt: maker
|
||||||
|
|
||||||
|
# Voici quelques exemples fréquents de fausses règles : all, make, clean,
|
||||||
|
# install...
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Variables automatiques et wildcards
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Utilise un wildcard pour des noms de fichier
|
||||||
|
process: fichier*.txt
|
||||||
|
@echo $^ # $^ est une variable contenant la liste des dépendances de la
|
||||||
|
# cible actuelle.
|
||||||
|
@echo $@ # $@ est le nom de la cible actuelle. En cas de cibles
|
||||||
|
# multiples, $@ est le nom de la cible ayant causé l'exécution
|
||||||
|
# de cette règle.
|
||||||
|
@echo $< # $< contient la première dépendance.
|
||||||
|
@echo $? # $? contient la liste des dépendances qui ne sont pas à jour.
|
||||||
|
@echo $+ # $+ contient la liste des dépendances avec d'éventuels
|
||||||
|
# duplicatas, contrairement à $^.
|
||||||
|
@echo $| # $| contient la liste des cibles ayant préséance sur la cible
|
||||||
|
# actuelle.
|
||||||
|
|
||||||
|
# Même si la définition de la règle est scindée en plusieurs morceaux, $^
|
||||||
|
# listera toutes les dépendances indiquées.
|
||||||
|
process: ex1.txt fichier0.txt
|
||||||
|
# Ici, fichier0.txt est un duplicata dans $+.
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Pattern matching
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# En utilisant le pattern matching, on peut par exemple créer des règles pour
|
||||||
|
# convertir les fichiers d'un certain format dans un autre.
|
||||||
|
%.png: %.svg
|
||||||
|
inkscape --export-png $^
|
||||||
|
|
||||||
|
# Make exécute une règle même si le fichier correspondant est situé dans un sous
|
||||||
|
# dossier. En cas de conflit, la règle avec la meilleure correspondance est
|
||||||
|
# choisie.
|
||||||
|
small/%.png: %.svg
|
||||||
|
inkscape --export-png --export-dpi 30 $^
|
||||||
|
|
||||||
|
# Dans ce type de conflit (même cible, même dépendances), make exécutera la
|
||||||
|
# dernière règle déclarée...
|
||||||
|
%.png: %.svg
|
||||||
|
@echo cette règle est choisie
|
||||||
|
|
||||||
|
# Dans ce type de conflit (même cible mais pas les mêmes dépendances), make
|
||||||
|
# exécutera la première règle pouvant être exécutée.
|
||||||
|
%.png: %.ps
|
||||||
|
@echo cette règle n\'est pas choisie si *.svg et *.ps sont présents
|
||||||
|
|
||||||
|
# Make a des règles pré établies. Par exemple, il sait comment créer la cible
|
||||||
|
# *.o à partir de *.c.
|
||||||
|
|
||||||
|
# Les makefiles plus vieux utilisent un matching par extension de fichier.
|
||||||
|
.png.ps:
|
||||||
|
@echo cette règle est similaire à une règle par pattern matching
|
||||||
|
|
||||||
|
# Utiliser cette règle spéciale pour déclarer une règle comme ayant un
|
||||||
|
# matching par extension de fichier.
|
||||||
|
.SUFFIXES: .png
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Variables, ou macros
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Les variables sont des chaînes de caractères.
|
||||||
|
|
||||||
|
variable = Ted
|
||||||
|
variable2="Sarah"
|
||||||
|
|
||||||
|
echo:
|
||||||
|
@echo $(variable)
|
||||||
|
@echo ${variable2}
|
||||||
|
@echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) !
|
||||||
|
@echo $(variable3) # Les variables non déclarées valent "" (chaîne vide).
|
||||||
|
|
||||||
|
# Les variables sont déclarées de 4 manières, de la plus grande priorité à la
|
||||||
|
# plus faible :
|
||||||
|
# 1 : dans la ligne de commande qui invoque make,
|
||||||
|
# 2 : dans le makefile,
|
||||||
|
# 3 : dans les variables d’environnement du terminal qui invoque make,
|
||||||
|
# 4 : les variables prédéfinies.
|
||||||
|
|
||||||
|
# Assigne la variable si une variable d’environnement du même nom n'existe pas
|
||||||
|
# déjà.
|
||||||
|
variable4 ?= Jean
|
||||||
|
|
||||||
|
# Empêche cette variable d'être modifiée par la ligne de commande.
|
||||||
|
override variable5 = David
|
||||||
|
|
||||||
|
# Concatène à une variable (avec un espace avant).
|
||||||
|
variable4 +=gris
|
||||||
|
|
||||||
|
# Assignations de variable pour les règles correspondant à un pattern
|
||||||
|
# (spécifique à GNU make).
|
||||||
|
*.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous
|
||||||
|
# leurs descendants, la variable variable2 vaudra
|
||||||
|
# "Sara".
|
||||||
|
# Si le jeux des dépendances et descendances devient vraiment trop compliqué,
|
||||||
|
# des incohérences peuvent survenir.
|
||||||
|
|
||||||
|
# Certaines variables sont prédéfinies par make :
|
||||||
|
affiche_predefinies:
|
||||||
|
echo $(CC)
|
||||||
|
echo ${CXX}
|
||||||
|
echo $(FC)
|
||||||
|
echo ${CFLAGS}
|
||||||
|
echo $(CPPFLAGS)
|
||||||
|
echo ${CXXFLAGS}
|
||||||
|
echo $(LDFLAGS)
|
||||||
|
echo ${LDLIBS}
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Variables : le retour
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Les variables sont évaluées à chaque instance, ce qui peut être coûteux en
|
||||||
|
# calculs. Pour parer à ce problème, il existe dans GNU make une seconde
|
||||||
|
# manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule
|
||||||
|
# fois seulement.
|
||||||
|
|
||||||
|
var := A B C
|
||||||
|
var2 ::= $(var) D E F # := et ::= sont équivalents.
|
||||||
|
|
||||||
|
# Ces variables sont évaluées procéduralement (i.e. dans leur ordre
|
||||||
|
# d'apparition), contrairement aux règles par exemple !
|
||||||
|
|
||||||
|
# Ceci ne fonctionne pas.
|
||||||
|
var3 ::= $(var4) et fais de beaux rêves
|
||||||
|
var4 ::= bonne nuit
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Fonctions
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Make a une multitude de fonctions. La syntaxe générale est
|
||||||
|
# $(fonction arg0,arg1,arg2...).
|
||||||
|
|
||||||
|
# Quelques exemples :
|
||||||
|
|
||||||
|
fichiers_source = $(wildcard *.c */*.c)
|
||||||
|
fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source))
|
||||||
|
|
||||||
|
ls: * src/*
|
||||||
|
@echo $(filter %.txt, $^)
|
||||||
|
@echo $(notdir $^)
|
||||||
|
@echo $(join $(dir $^),$(notdir $^))
|
||||||
|
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
# Directives
|
||||||
|
#-----------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Inclut d'autres makefiles.
|
||||||
|
include meuh.mk
|
||||||
|
|
||||||
|
# Branchements conditionnels.
|
||||||
|
sport = tennis
|
||||||
|
report:
|
||||||
|
ifeq ($(sport),tennis) # Il y a aussi ifneq.
|
||||||
|
@echo 'jeu, set et match'
|
||||||
|
else
|
||||||
|
@echo "C'est pas ici Wimbledon ?"
|
||||||
|
endif
|
||||||
|
|
||||||
|
truc = true
|
||||||
|
ifdef $(truc) # Il y a aussi ifndef.
|
||||||
|
machin = 'salut'
|
||||||
|
endif
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quelques références
|
||||||
|
|
||||||
|
### En français
|
||||||
|
|
||||||
|
+ [Introduction à Makefile (developpez.com)]
|
||||||
|
(http://gl.developpez.com/tutoriel/outil/makefile/),
|
||||||
|
+ [Compilez sous GNU/Linux ! (openclassrooms)]
|
||||||
|
(https://openclassrooms.com/courses/compilez-sous-gnu-linux).
|
||||||
|
|
||||||
|
### En anglais
|
||||||
|
|
||||||
|
+ [Documentation de GNU make](https://www.gnu.org/software/make/manual/),
|
||||||
|
+ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/),
|
||||||
|
+ Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html)
|
||||||
|
[ex28](http://c.learncodethehardway.org/book/ex28.html).
|
@ -2,7 +2,7 @@
|
|||||||
language: markdown
|
language: markdown
|
||||||
contributors:
|
contributors:
|
||||||
- ["Andrei Curelaru", "http://www.infinidad.fr"]
|
- ["Andrei Curelaru", "http://www.infinidad.fr"]
|
||||||
filename: markdown.md
|
filename: markdown-fr.md
|
||||||
lang: fr-fr
|
lang: fr-fr
|
||||||
---
|
---
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
---
|
---
|
||||||
|
|
||||||
language: Objective-C
|
language: Objective-C
|
||||||
contributors:
|
contributors:
|
||||||
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
|
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
|
||||||
@ -9,7 +8,6 @@ translators:
|
|||||||
- ["Yannick Loriot", "https://github.com/YannickL"]
|
- ["Yannick Loriot", "https://github.com/YannickL"]
|
||||||
filename: LearnObjectiveC-fr.m
|
filename: LearnObjectiveC-fr.m
|
||||||
lang: fr-fr
|
lang: fr-fr
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
|
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
|
||||||
@ -519,6 +517,7 @@ __unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'es
|
|||||||
// l'objet est supprimé
|
// l'objet est supprimé
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Lectures Complémentaires
|
## Lectures Complémentaires
|
||||||
|
|
||||||
[La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C)
|
[La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C)
|
||||||
|
174
fr-fr/perl-fr.html.markdown
Normal file
174
fr-fr/perl-fr.html.markdown
Normal file
@ -0,0 +1,174 @@
|
|||||||
|
---
|
||||||
|
name: perl
|
||||||
|
category: language
|
||||||
|
language: perl
|
||||||
|
filename: learnperl-fr.pl
|
||||||
|
contributors:
|
||||||
|
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
||||||
|
- ["Matteo Taroli", "http://www.matteotaroli.be"]
|
||||||
|
translators:
|
||||||
|
- ["Matteo Taroli", "http://www.matteotaroli.be"]
|
||||||
|
lang: fr-fr
|
||||||
|
---
|
||||||
|
Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
|
||||||
|
|
||||||
|
Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
|
||||||
|
est autant adapté à un prototypage rapide qu'à des projets de grande envergure.
|
||||||
|
|
||||||
|
```perl
|
||||||
|
# Les commentaires en une ligne commencent par un dièse
|
||||||
|
|
||||||
|
|
||||||
|
#### Types de variables de Perl
|
||||||
|
|
||||||
|
# Les variables comment par un symbole précisant le type.
|
||||||
|
# Un nom de variable valide commence par une lettre ou un underscore,
|
||||||
|
# suivi d'un nombre quelconque de lettres, chiffres ou underscores.
|
||||||
|
|
||||||
|
### Perl a trois types principaux de variables: $scalaire, @tableau and %hash
|
||||||
|
|
||||||
|
## Scalaires
|
||||||
|
# Un scalaire représente une valeur unique :
|
||||||
|
my $animal = "chameau";
|
||||||
|
my $reponse = 42;
|
||||||
|
|
||||||
|
# Les valeurs scalaires peuvent être des strings, des entiers ou des nombres à virgule flottante
|
||||||
|
# et Perl les convertira automatiquement entre elles quand nécessaire.
|
||||||
|
|
||||||
|
## Tableaux
|
||||||
|
# Un tableau représente une liste de valeurs :
|
||||||
|
my @animaux = ("chameau", "lama", "chouette");
|
||||||
|
my @nombres = (23, 42, 69);
|
||||||
|
my @melange = ("chameau", 42, 1.23);
|
||||||
|
|
||||||
|
## Hashes
|
||||||
|
# Un hash représente un ensemble de paires de clé/valeur :
|
||||||
|
my %fruit_couleur = ("pomme", "rouge", "banane", "jaune");
|
||||||
|
|
||||||
|
# Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment :
|
||||||
|
|
||||||
|
my %fruit_couleur = (
|
||||||
|
pomme => "rouge",
|
||||||
|
banane => "jaune"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata
|
||||||
|
# (perldoc perldata)
|
||||||
|
|
||||||
|
# Des types de données plus complexes peuvent être construits en utilisant des références,
|
||||||
|
# vous permettant de construire des listes et des hashes à l'intérieur d'autres listes et hashes.
|
||||||
|
|
||||||
|
#### Conditions et boucles
|
||||||
|
|
||||||
|
# Perl possède la plupart des conditions et boucles habituelles.
|
||||||
|
|
||||||
|
if ($var) {
|
||||||
|
...
|
||||||
|
} elsif ($var eq 'bar') {
|
||||||
|
...
|
||||||
|
} else {
|
||||||
|
...
|
||||||
|
}
|
||||||
|
|
||||||
|
unless (condition) {
|
||||||
|
...
|
||||||
|
}
|
||||||
|
# Ceci est fourni en tant que version plus lisible de "if (!condition)"
|
||||||
|
|
||||||
|
# la postcondition à la sauce Perl
|
||||||
|
|
||||||
|
print "Yow!" if $zippy;
|
||||||
|
print "Nous n'avons pas de banane." unless $bananes;
|
||||||
|
|
||||||
|
# while
|
||||||
|
while (condition) {
|
||||||
|
...
|
||||||
|
}
|
||||||
|
|
||||||
|
# boucle for et iteration
|
||||||
|
for (my $i = 0; $i < $max; $i++) {
|
||||||
|
print "l'index est $i";
|
||||||
|
}
|
||||||
|
|
||||||
|
for (my $i = 0; $i < @elements; $i++) {
|
||||||
|
print "L'élément courant est " . $elements[$i];
|
||||||
|
}
|
||||||
|
|
||||||
|
for my $element (@elements) {
|
||||||
|
print $element;
|
||||||
|
}
|
||||||
|
|
||||||
|
# implicitement
|
||||||
|
|
||||||
|
# La variable de contexte scalaire $_ est utilisée par défaut dans différentes
|
||||||
|
# situations, comme par exemple dans la boucle foreach ou en argument par défaut
|
||||||
|
# de la plupart des fonctions pour en simplifier l'écriture.
|
||||||
|
|
||||||
|
# Dans l'exemple suivant, $_ prends successivement la valeur de
|
||||||
|
# chaque élément de la liste.
|
||||||
|
|
||||||
|
for (@elements) {
|
||||||
|
print; # affiche le contenu de $_
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#### Expressions régulières
|
||||||
|
|
||||||
|
# Le support des expressions régulières par Perl est aussi large que profond
|
||||||
|
# et est sujet à une longue documentation sur perlrequick, perlretut et ailleurs.
|
||||||
|
# Cependant, pour faire court :
|
||||||
|
|
||||||
|
# Simple correspondance
|
||||||
|
if (/foo/) { ... } # vrai si $_ contient "foo"
|
||||||
|
if ($a =~ /foo/) { ... } # vrai si $a contient "foo"
|
||||||
|
|
||||||
|
# Simple substitution
|
||||||
|
|
||||||
|
$a =~ s/foo/bar/; # remplace le premier foo par bar dans $a
|
||||||
|
$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a
|
||||||
|
|
||||||
|
|
||||||
|
#### Fichiers et E/S
|
||||||
|
|
||||||
|
# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()".
|
||||||
|
|
||||||
|
open(my $in, "<", "input.txt") or die "Impossible d'ouvrir input.txt: $!";
|
||||||
|
open(my $out, ">", "output.txt") or die "Impossible d'ouvrir output.txt: $!";
|
||||||
|
open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!";
|
||||||
|
|
||||||
|
# Vous pouvez lire depuis un descripteur de fichier grâce à l'opérateur "<>".
|
||||||
|
# Dans un contexte scalaire, il lit une seule ligne depuis le descripteur de fichier
|
||||||
|
# et dans un contexte de liste, il lit le fichier complet, assignant chaque ligne à un
|
||||||
|
# élément de la liste :
|
||||||
|
|
||||||
|
my $ligne = <$in>
|
||||||
|
my $lignes = <$in>
|
||||||
|
|
||||||
|
#### Ecrire des fonctions
|
||||||
|
|
||||||
|
# Ecrire des fonctions est facile :
|
||||||
|
|
||||||
|
sub logger {
|
||||||
|
my $logmessage = shift;
|
||||||
|
|
||||||
|
open my $logfile, ">>", "my.log" or die "Impossible d'ouvrir my.log: $!";
|
||||||
|
|
||||||
|
print $logfile $logmessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Maintenant, nous pouvons utiliser cette fonction comme n'importe quelle fonction intégrée :
|
||||||
|
|
||||||
|
logger("On a une fonction de logging!!");
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Utiliser des modules Perl
|
||||||
|
|
||||||
|
Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl.
|
||||||
|
|
||||||
|
Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser.
|
||||||
|
|
||||||
|
#### Pour en savoir plus
|
||||||
|
- [perl-tutorial](http://perl-tutorial.org/)
|
||||||
|
- [Learn at www.perl.com](http://www.perl.org/learn.html)
|
||||||
|
- [perldoc](http://perldoc.perl.org/)
|
||||||
|
- and perl built-in : `perldoc perlintro`
|
@ -627,7 +627,7 @@ Human.grunt() # => "*grunt*"
|
|||||||
|
|
||||||
# On peut importer des modules
|
# On peut importer des modules
|
||||||
import math
|
import math
|
||||||
print(math.sqrt(16)) # => 4
|
print(math.sqrt(16)) # => 4.0
|
||||||
|
|
||||||
# On peut importer des fonctions spécifiques d'un module
|
# On peut importer des fonctions spécifiques d'un module
|
||||||
from math import ceil, floor
|
from math import ceil, floor
|
||||||
|
@ -87,22 +87,22 @@ mySearch = function(src: string, sub: string) {
|
|||||||
|
|
||||||
// Les membres des classes sont publiques par défaut.
|
// Les membres des classes sont publiques par défaut.
|
||||||
class Point {
|
class Point {
|
||||||
// Propriétés
|
// Propriétés
|
||||||
x: number;
|
x: number;
|
||||||
|
|
||||||
// Constructeur - Les mots clés "public" et "private" dans ce contexte
|
// Constructeur - Les mots clés "public" et "private" dans ce contexte
|
||||||
// génèrent le code de la propriété et son initialisation dans le
|
// génèrent le code de la propriété et son initialisation dans le
|
||||||
// constructeur. Ici, "y" sera défini de la même façon que "x",
|
// constructeur. Ici, "y" sera défini de la même façon que "x",
|
||||||
// mais avec moins de code. Les valeurs par défaut sont supportées.
|
// mais avec moins de code. Les valeurs par défaut sont supportées.
|
||||||
constructor(x: number, public y: number = 0) {
|
constructor(x: number, public y: number = 0) {
|
||||||
this.x = x;
|
this.x = x;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fonctions
|
// Fonctions
|
||||||
dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
||||||
|
|
||||||
// Membres statiques
|
// Membres statiques
|
||||||
static origin = new Point(0, 0);
|
static origin = new Point(0, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
var p1 = new Point(10 ,20);
|
var p1 = new Point(10 ,20);
|
||||||
@ -110,17 +110,17 @@ var p2 = new Point(25); // y sera 0
|
|||||||
|
|
||||||
// Héritage
|
// Héritage
|
||||||
class Point3D extends Point {
|
class Point3D extends Point {
|
||||||
constructor(x: number, y: number, public z: number = 0) {
|
constructor(x: number, y: number, public z: number = 0) {
|
||||||
// Un appel explicite au constructeur de la super classe
|
// Un appel explicite au constructeur de la super classe
|
||||||
// est obligatoire.
|
// est obligatoire.
|
||||||
super(x, y);
|
super(x, y);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Redéfinition
|
// Redéfinition
|
||||||
dist() {
|
dist() {
|
||||||
var d = super.dist();
|
var d = super.dist();
|
||||||
return Math.sqrt(d * d + this.z * this.z);
|
return Math.sqrt(d * d + this.z * this.z);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modules, "." peut être utilisé comme un séparateur de sous modules.
|
// Modules, "." peut être utilisé comme un séparateur de sous modules.
|
||||||
@ -144,19 +144,19 @@ var s2 = new G.Square(10);
|
|||||||
// Génériques
|
// Génériques
|
||||||
// Classes
|
// Classes
|
||||||
class Tuple<T1, T2> {
|
class Tuple<T1, T2> {
|
||||||
constructor(public item1: T1, public item2: T2) {
|
constructor(public item1: T1, public item2: T2) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Interfaces
|
// Interfaces
|
||||||
interface Pair<T> {
|
interface Pair<T> {
|
||||||
item1: T;
|
item1: T;
|
||||||
item2: T;
|
item2: T;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Et fonctions
|
// Et fonctions
|
||||||
var pairToTuple = function<T>(p: Pair<T>) {
|
var pairToTuple = function<T>(p: Pair<T>) {
|
||||||
return new Tuple(p.item1, p.item2);
|
return new Tuple(p.item1, p.item2);
|
||||||
};
|
};
|
||||||
|
|
||||||
var tuple = pairToTuple({ item1:"hello", item2:"world"});
|
var tuple = pairToTuple({ item1:"hello", item2:"world"});
|
||||||
|
167
fr-fr/wolfram-fr.html.markdown
Normal file
167
fr-fr/wolfram-fr.html.markdown
Normal file
@ -0,0 +1,167 @@
|
|||||||
|
---
|
||||||
|
language: wolfram
|
||||||
|
contributors:
|
||||||
|
- ["hyphz", "http://github.com/hyphz/"]
|
||||||
|
translators:
|
||||||
|
- ["altaris", "http://github.com/altaris/"]
|
||||||
|
filename: learnwolfram-fr.nb
|
||||||
|
lang: fr-fr
|
||||||
|
---
|
||||||
|
|
||||||
|
Le langage Wolfram est utilisé dans les programmes suivants :
|
||||||
|
* La ligne de commandes interactive noyau du Raspberry Pi, mais elle ne peut pas
|
||||||
|
gérer des éléments graphiques.
|
||||||
|
* _Mathematica_, un éditeur de texte riche spécialisé pour les mathématiques :
|
||||||
|
appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule
|
||||||
|
contenant le résultat.
|
||||||
|
* _Wolfram Wokbench_, une variante d'Eclipse spécialisée pour le langage
|
||||||
|
Wolfram.
|
||||||
|
|
||||||
|
Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant, le
|
||||||
|
copier-coller directement dans Mathematica peut causer des problèmes de
|
||||||
|
formatage, car il ne contient aucune information de mise en page.
|
||||||
|
|
||||||
|
```
|
||||||
|
(* Ceci est un commentaire *)
|
||||||
|
|
||||||
|
(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des
|
||||||
|
cellules de texte et insérer de jolies images *)
|
||||||
|
|
||||||
|
(* Saisissez une opération et appuyez sur Shift + Entrée pour obtenir le
|
||||||
|
résultat *)
|
||||||
|
2*2 (* 4 *)
|
||||||
|
5+8 (* 13 *)
|
||||||
|
|
||||||
|
(* Appels de fonction *)
|
||||||
|
Sin[Pi/2] (* 1 *)
|
||||||
|
(* Syntaxe alternative pour les appels de fonction à 1 paramètre *)
|
||||||
|
Sin@(Pi/2) (* 1 *)
|
||||||
|
(Pi/2) // Sin (* 1 *)
|
||||||
|
|
||||||
|
(* Attention : le langage est sensible à la casse ! *)
|
||||||
|
|
||||||
|
(* Toutes les expressions sont en réalité des appels de fonction *)
|
||||||
|
Times[2, 2] (* 4 *)
|
||||||
|
Plus[5, 8] (* 13 *)
|
||||||
|
|
||||||
|
(* Utiliser une variable pour la première fois la déclare globalement *)
|
||||||
|
x = 5 (* 5 *)
|
||||||
|
x == 5 (* True, l'assignation et le test d'égalité est écrit comme
|
||||||
|
en C *)
|
||||||
|
x (* 5 *)
|
||||||
|
x = x + 5 (* 10 *)
|
||||||
|
x (* 10 *)
|
||||||
|
Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *)
|
||||||
|
x (* 20 *)
|
||||||
|
|
||||||
|
(* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des
|
||||||
|
variables non déclarées est légal *)
|
||||||
|
truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation
|
||||||
|
s'arrête là *)
|
||||||
|
truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *)
|
||||||
|
% (* 15 + truc, % représente le dernier résultat *)
|
||||||
|
% - truc (* 15, les variables non déclarées peuvent quand même
|
||||||
|
s'annuler *)
|
||||||
|
chose = truc + 5 (* Attention : chose est ici une expression et non un nombre *)
|
||||||
|
|
||||||
|
(* Déclaration d'une fonction *)
|
||||||
|
Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme
|
||||||
|
à droite *)
|
||||||
|
Double[10] (* 20 *)
|
||||||
|
Double[Sin[Pi/2]] (* 2 *)
|
||||||
|
Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets
|
||||||
|
fermants si moches *)
|
||||||
|
(Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans
|
||||||
|
l'ordre d'appel *)
|
||||||
|
|
||||||
|
(* En programmation impérative, utiliser ; pour séparer les expressions *)
|
||||||
|
Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires
|
||||||
|
car ; est prioritaire sur := *)
|
||||||
|
Salut[] (* Hello World *)
|
||||||
|
|
||||||
|
(* Boucles For à la C *)
|
||||||
|
Compter[x_] := For[y=0, y<x, y++, (Print[y])] (* L'évaluation des boucles For
|
||||||
|
se fait comme en C *)
|
||||||
|
Compter[5] (* 0 1 2 3 4 *)
|
||||||
|
|
||||||
|
(* Boucles While *)
|
||||||
|
x = 0; While[x < 2, (Print@x; x++)] (* De nouveau, comme en C *)
|
||||||
|
|
||||||
|
(* Expressions conditionnelles et If *)
|
||||||
|
x = 8; If[x==8, Print@"Huit", Print@"Pas huit"] (* If [condition, si vrai,
|
||||||
|
si faux] *)
|
||||||
|
Switch[x, 2, Print@"Deux", 8, Print@"Huit"] (* Switch par valeur *)
|
||||||
|
Which[x==2, Print@"Deux", x==8, Print@"Huit"] (* Switch du type if, else if,
|
||||||
|
else if, ..., else *)
|
||||||
|
|
||||||
|
(* Les variables autres que les paramètres de fonctions sont par défaut
|
||||||
|
globales, même à l'intérieur des fonctions *)
|
||||||
|
y = 10 (* 10, y est une variable globale *)
|
||||||
|
Compter[5] (* 0 1 2 3 4 *)
|
||||||
|
y (* 5, y a été modifiée par Compter *)
|
||||||
|
x = 20 (* 20, x est une variable globale *)
|
||||||
|
Compter[5] (* 0 1 2 3 4 *)
|
||||||
|
x (* 20, dans Compter, le paramètre x masque la variable
|
||||||
|
globale x *)
|
||||||
|
|
||||||
|
(* La fonction Module permet d'utiliser des variables locales *)
|
||||||
|
MieuxCompter[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])]
|
||||||
|
y = 20 (* y est une variable globale *)
|
||||||
|
MieuxCompter[5] (* 0 1 2 3 4 *)
|
||||||
|
y (* 20, y n'a pas été modifiée car le y du Module masque le
|
||||||
|
y global. C'est bien mieux comme ça ! *)
|
||||||
|
|
||||||
|
(* Module permet de faire des déclarations globales aussi *)
|
||||||
|
Module[{compte}, compte=0; (* compte est une variable locale *)
|
||||||
|
(Incrementer[] := ++compte); (* Ce module déclare des fonctions, mais elles
|
||||||
|
ne sont globales. Elles ont cependant accès
|
||||||
|
aux variables locales au module. *)
|
||||||
|
(Decrementer[] := --compte)]
|
||||||
|
compte (* compte, car il n'y a pas de variable globale nommée
|
||||||
|
compte *)
|
||||||
|
Incrementer[] (* 1, la fonction utilise la variable compte du module *)
|
||||||
|
Incrementer[] (* 2, le précédent appel de Incrementer a modifié compte *)
|
||||||
|
Decrementer[] (* 1 *)
|
||||||
|
compte (* compte, car il n'existe toujours pas de variable globale
|
||||||
|
nommé compte *)
|
||||||
|
|
||||||
|
(* Listes *)
|
||||||
|
liste = {1, 2, 3, 4} (* {1, 2, 3, 4} *)
|
||||||
|
liste[[1]] (* 1, les indexes commencent à 1 et non 0 !!! *)
|
||||||
|
Map[Double, liste] (* {2, 4, 6, 8}, appliquer une fonction à une liste de
|
||||||
|
manière fonctionnelle *)
|
||||||
|
Double /@ liste (* {2, 4, 6, 8}, syntaxe abrégée de la ligne
|
||||||
|
précédente *)
|
||||||
|
Scan[Print, liste] (* 1 2 3 4, boucle impérative sur une liste *)
|
||||||
|
Fold[Plus, 0, liste] (* 10 (0+1+2+3+4) *)
|
||||||
|
FoldList[Plus, 0, liste] (* {0, 1, 3, 6, 10}, variante de la fonction
|
||||||
|
précédente qui donne aussi les résultats
|
||||||
|
intermédiaires *)
|
||||||
|
Append[liste, 5] (* {1, 2, 3, 4, 5}, liste n'est pas modifiée... *)
|
||||||
|
Prepend[liste, 5] (* {5, 1, 2, 3, 4}, ... mais elle peut l'être en
|
||||||
|
écrivant "liste = " *)
|
||||||
|
Join[liste, {3, 4}] (* {1, 2, 3, 4, 3, 4} *)
|
||||||
|
liste[[2]] = 5 (* {1, 5, 3, 4}, ceci modifie bien la liste *)
|
||||||
|
|
||||||
|
(* Tables associatives, ou dictionnaires *)
|
||||||
|
table = <|"Vert" -> 2, "Rouge" -> 1|> (* Crée une table associative *)
|
||||||
|
table[["Vert"]] (* 2, l'utilise *)
|
||||||
|
table[["Vert"]] := 5 (* 5, la modifie *)
|
||||||
|
table[["Bleu"]] := 3.5 (* 3.5, l'étend *)
|
||||||
|
KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *)
|
||||||
|
Keys[table] (* {Rouge, Bleu} *)
|
||||||
|
Values[table] (* {1, 3.5} *)
|
||||||
|
|
||||||
|
(* Pour finir, toute bonne démonstration du langage Wolfram contient un
|
||||||
|
Manipulate ! *)
|
||||||
|
Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui
|
||||||
|
affiche y^2, permettant à l'utilisateur de
|
||||||
|
modifier la valeur de y grâce à un contrôle
|
||||||
|
allant de 0 à 20. Ne fonctionne que si le
|
||||||
|
logiciel utilisé gère les éléments graphiques. *)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Envie d'aller plus loin ?
|
||||||
|
|
||||||
|
* [Documentation du langage Wolfram (en anglais)]
|
||||||
|
(http://reference.wolfram.com/language/)
|
@ -31,14 +31,14 @@ If you want to try out the code below, you can go to [tryfsharp.org](http://www.
|
|||||||
// The "let" keyword defines an (immutable) value
|
// The "let" keyword defines an (immutable) value
|
||||||
let myInt = 5
|
let myInt = 5
|
||||||
let myFloat = 3.14
|
let myFloat = 3.14
|
||||||
let myString = "hello" //note that no types needed
|
let myString = "hello" // note that no types needed
|
||||||
|
|
||||||
// ------ Lists ------
|
// ------ Lists ------
|
||||||
let twoToFive = [2;3;4;5] // Square brackets create a list with
|
let twoToFive = [2; 3; 4; 5] // Square brackets create a list with
|
||||||
// semicolon delimiters.
|
// semicolon delimiters.
|
||||||
let oneToFive = 1 :: twoToFive // :: creates list with new 1st element
|
let oneToFive = 1 :: twoToFive // :: creates list with new 1st element
|
||||||
// The result is [1;2;3;4;5]
|
// The result is [1; 2; 3; 4; 5]
|
||||||
let zeroToFive = [0;1] @ twoToFive // @ concats two lists
|
let zeroToFive = [0; 1] @ twoToFive // @ concats two lists
|
||||||
|
|
||||||
// IMPORTANT: commas are never used as delimiters, only semicolons!
|
// IMPORTANT: commas are never used as delimiters, only semicolons!
|
||||||
|
|
||||||
@ -53,7 +53,7 @@ add 2 3 // Now run the function.
|
|||||||
|
|
||||||
// to define a multiline function, just use indents. No semicolons needed.
|
// to define a multiline function, just use indents. No semicolons needed.
|
||||||
let evens list =
|
let evens list =
|
||||||
let isEven x = x%2 = 0 // Define "isEven" as a sub function
|
let isEven x = x % 2 = 0 // Define "isEven" as a sub function
|
||||||
List.filter isEven list // List.filter is a library function
|
List.filter isEven list // List.filter is a library function
|
||||||
// with two parameters: a boolean function
|
// with two parameters: a boolean function
|
||||||
// and a list to work on
|
// and a list to work on
|
||||||
@ -75,7 +75,7 @@ let sumOfSquaresTo100piped =
|
|||||||
|
|
||||||
// you can define lambdas (anonymous functions) using the "fun" keyword
|
// you can define lambdas (anonymous functions) using the "fun" keyword
|
||||||
let sumOfSquaresTo100withFun =
|
let sumOfSquaresTo100withFun =
|
||||||
[1..100] |> List.map (fun x -> x*x) |> List.sum
|
[1..100] |> List.map (fun x -> x * x) |> List.sum
|
||||||
|
|
||||||
// In F# there is no "return" keyword. A function always
|
// In F# there is no "return" keyword. A function always
|
||||||
// returns the value of the last expression used.
|
// returns the value of the last expression used.
|
||||||
@ -109,7 +109,7 @@ optionPatternMatch invalidValue
|
|||||||
// The printf/printfn functions are similar to the
|
// The printf/printfn functions are similar to the
|
||||||
// Console.Write/WriteLine functions in C#.
|
// Console.Write/WriteLine functions in C#.
|
||||||
printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true
|
printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true
|
||||||
printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
|
printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4]
|
||||||
|
|
||||||
// There are also sprintf/sprintfn functions for formatting data
|
// There are also sprintf/sprintfn functions for formatting data
|
||||||
// into a string, similar to String.Format in C#.
|
// into a string, similar to String.Format in C#.
|
||||||
@ -131,19 +131,19 @@ module FunctionExamples =
|
|||||||
|
|
||||||
// basic usage of a function
|
// basic usage of a function
|
||||||
let a = add 1 2
|
let a = add 1 2
|
||||||
printfn "1+2 = %i" a
|
printfn "1 + 2 = %i" a
|
||||||
|
|
||||||
// partial application to "bake in" parameters
|
// partial application to "bake in" parameters
|
||||||
let add42 = add 42
|
let add42 = add 42
|
||||||
let b = add42 1
|
let b = add42 1
|
||||||
printfn "42+1 = %i" b
|
printfn "42 + 1 = %i" b
|
||||||
|
|
||||||
// composition to combine functions
|
// composition to combine functions
|
||||||
let add1 = add 1
|
let add1 = add 1
|
||||||
let add2 = add 2
|
let add2 = add 2
|
||||||
let add3 = add1 >> add2
|
let add3 = add1 >> add2
|
||||||
let c = add3 7
|
let c = add3 7
|
||||||
printfn "3+7 = %i" c
|
printfn "3 + 7 = %i" c
|
||||||
|
|
||||||
// higher order functions
|
// higher order functions
|
||||||
[1..10] |> List.map add3 |> printfn "new list is %A"
|
[1..10] |> List.map add3 |> printfn "new list is %A"
|
||||||
@ -151,7 +151,7 @@ module FunctionExamples =
|
|||||||
// lists of functions, and more
|
// lists of functions, and more
|
||||||
let add6 = [add1; add2; add3] |> List.reduce (>>)
|
let add6 = [add1; add2; add3] |> List.reduce (>>)
|
||||||
let d = add6 7
|
let d = add6 7
|
||||||
printfn "1+2+3+7 = %i" d
|
printfn "1 + 2 + 3 + 7 = %i" d
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// Lists and collection
|
// Lists and collection
|
||||||
@ -168,12 +168,12 @@ module FunctionExamples =
|
|||||||
module ListExamples =
|
module ListExamples =
|
||||||
|
|
||||||
// lists use square brackets
|
// lists use square brackets
|
||||||
let list1 = ["a";"b"]
|
let list1 = ["a"; "b"]
|
||||||
let list2 = "c" :: list1 // :: is prepending
|
let list2 = "c" :: list1 // :: is prepending
|
||||||
let list3 = list1 @ list2 // @ is concat
|
let list3 = list1 @ list2 // @ is concat
|
||||||
|
|
||||||
// list comprehensions (aka generators)
|
// list comprehensions (aka generators)
|
||||||
let squares = [for i in 1..10 do yield i*i]
|
let squares = [for i in 1..10 do yield i * i]
|
||||||
|
|
||||||
// prime number generator
|
// prime number generator
|
||||||
let rec sieve = function
|
let rec sieve = function
|
||||||
@ -190,8 +190,8 @@ module ListExamples =
|
|||||||
| [first; second] -> printfn "list is %A and %A" first second
|
| [first; second] -> printfn "list is %A and %A" first second
|
||||||
| _ -> printfn "the list has more than two elements"
|
| _ -> printfn "the list has more than two elements"
|
||||||
|
|
||||||
listMatcher [1;2;3;4]
|
listMatcher [1; 2; 3; 4]
|
||||||
listMatcher [1;2]
|
listMatcher [1; 2]
|
||||||
listMatcher [1]
|
listMatcher [1]
|
||||||
listMatcher []
|
listMatcher []
|
||||||
|
|
||||||
@ -219,7 +219,7 @@ module ListExamples =
|
|||||||
module ArrayExamples =
|
module ArrayExamples =
|
||||||
|
|
||||||
// arrays use square brackets with bar
|
// arrays use square brackets with bar
|
||||||
let array1 = [| "a";"b" |]
|
let array1 = [| "a"; "b" |]
|
||||||
let first = array1.[0] // indexed access using dot
|
let first = array1.[0] // indexed access using dot
|
||||||
|
|
||||||
// pattern matching for arrays is same as for lists
|
// pattern matching for arrays is same as for lists
|
||||||
@ -230,13 +230,13 @@ module ArrayExamples =
|
|||||||
| [| first; second |] -> printfn "array is %A and %A" first second
|
| [| first; second |] -> printfn "array is %A and %A" first second
|
||||||
| _ -> printfn "the array has more than two elements"
|
| _ -> printfn "the array has more than two elements"
|
||||||
|
|
||||||
arrayMatcher [| 1;2;3;4 |]
|
arrayMatcher [| 1; 2; 3; 4 |]
|
||||||
|
|
||||||
// Standard library functions just as for List
|
// Standard library functions just as for List
|
||||||
|
|
||||||
[| 1..10 |]
|
[| 1..10 |]
|
||||||
|> Array.map (fun i -> i+3)
|
|> Array.map (fun i -> i + 3)
|
||||||
|> Array.filter (fun i -> i%2 = 0)
|
|> Array.filter (fun i -> i % 2 = 0)
|
||||||
|> Array.iter (printfn "value is %i. ")
|
|> Array.iter (printfn "value is %i. ")
|
||||||
|
|
||||||
|
|
||||||
@ -248,14 +248,14 @@ module SequenceExamples =
|
|||||||
// sequences can use yield and
|
// sequences can use yield and
|
||||||
// can contain subsequences
|
// can contain subsequences
|
||||||
let strange = seq {
|
let strange = seq {
|
||||||
// "yield! adds one element
|
// "yield" adds one element
|
||||||
yield 1; yield 2;
|
yield 1; yield 2;
|
||||||
|
|
||||||
// "yield!" adds a whole subsequence
|
// "yield!" adds a whole subsequence
|
||||||
yield! [5..10]
|
yield! [5..10]
|
||||||
yield! seq {
|
yield! seq {
|
||||||
for i in 1..10 do
|
for i in 1..10 do
|
||||||
if i%2 = 0 then yield i }}
|
if i % 2 = 0 then yield i }}
|
||||||
// test
|
// test
|
||||||
strange |> Seq.toList
|
strange |> Seq.toList
|
||||||
|
|
||||||
@ -280,11 +280,11 @@ module DataTypeExamples =
|
|||||||
|
|
||||||
// Tuples are quick 'n easy anonymous types
|
// Tuples are quick 'n easy anonymous types
|
||||||
// -- Use a comma to create a tuple
|
// -- Use a comma to create a tuple
|
||||||
let twoTuple = 1,2
|
let twoTuple = 1, 2
|
||||||
let threeTuple = "a",2,true
|
let threeTuple = "a", 2, true
|
||||||
|
|
||||||
// Pattern match to unpack
|
// Pattern match to unpack
|
||||||
let x,y = twoTuple //sets x=1 y=2
|
let x, y = twoTuple // sets x = 1, y = 2
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Record types have named fields
|
// Record types have named fields
|
||||||
@ -297,7 +297,7 @@ module DataTypeExamples =
|
|||||||
let person1 = {First="John"; Last="Doe"}
|
let person1 = {First="John"; Last="Doe"}
|
||||||
|
|
||||||
// Pattern match to unpack
|
// Pattern match to unpack
|
||||||
let {First=first} = person1 //sets first="john"
|
let {First = first} = person1 // sets first="John"
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Union types (aka variants) have a set of choices
|
// Union types (aka variants) have a set of choices
|
||||||
@ -331,14 +331,14 @@ module DataTypeExamples =
|
|||||||
| Worker of Person
|
| Worker of Person
|
||||||
| Manager of Employee list
|
| Manager of Employee list
|
||||||
|
|
||||||
let jdoe = {First="John";Last="Doe"}
|
let jdoe = {First="John"; Last="Doe"}
|
||||||
let worker = Worker jdoe
|
let worker = Worker jdoe
|
||||||
|
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
// Modelling with types
|
// Modeling with types
|
||||||
// ------------------------------------
|
// ------------------------------------
|
||||||
|
|
||||||
// Union types are great for modelling state without using flags
|
// Union types are great for modeling state without using flags
|
||||||
type EmailAddress =
|
type EmailAddress =
|
||||||
| ValidEmailAddress of string
|
| ValidEmailAddress of string
|
||||||
| InvalidEmailAddress of string
|
| InvalidEmailAddress of string
|
||||||
@ -383,8 +383,8 @@ module DataTypeExamples =
|
|||||||
type Rank = Two | Three | Four | Five | Six | Seven | Eight
|
type Rank = Two | Three | Four | Five | Six | Seven | Eight
|
||||||
| Nine | Ten | Jack | Queen | King | Ace
|
| Nine | Ten | Jack | Queen | King | Ace
|
||||||
|
|
||||||
let hand = [ Club,Ace; Heart,Three; Heart,Ace;
|
let hand = [ Club, Ace; Heart, Three; Heart, Ace;
|
||||||
Spade,Jack; Diamond,Two; Diamond,Ace ]
|
Spade, Jack; Diamond, Two; Diamond, Ace ]
|
||||||
|
|
||||||
// sorting
|
// sorting
|
||||||
List.sort hand |> printfn "sorted hand is (low to high) %A"
|
List.sort hand |> printfn "sorted hand is (low to high) %A"
|
||||||
@ -419,14 +419,14 @@ module ActivePatternExamples =
|
|||||||
| _ -> printfn "%c is something else" ch
|
| _ -> printfn "%c is something else" ch
|
||||||
|
|
||||||
// print a list
|
// print a list
|
||||||
['a';'b';'1';' ';'-';'c'] |> List.iter printChar
|
['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar
|
||||||
|
|
||||||
// -----------------------------------
|
// -----------------------------------
|
||||||
// FizzBuzz using active patterns
|
// FizzBuzz using active patterns
|
||||||
// -----------------------------------
|
// -----------------------------------
|
||||||
|
|
||||||
// You can create partial matching patterns as well
|
// You can create partial matching patterns as well
|
||||||
// Just use undercore in the defintion, and return Some if matched.
|
// Just use underscore in the defintion, and return Some if matched.
|
||||||
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
|
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
|
||||||
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
|
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
|
||||||
|
|
||||||
@ -479,7 +479,7 @@ module AlgorithmExamples =
|
|||||||
List.concat [smallerElements; [firstElem]; largerElements]
|
List.concat [smallerElements; [firstElem]; largerElements]
|
||||||
|
|
||||||
// test
|
// test
|
||||||
sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
|
sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A"
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// Asynchronous Code
|
// Asynchronous Code
|
||||||
@ -526,7 +526,7 @@ module AsyncExample =
|
|||||||
|> Async.RunSynchronously // start them off
|
|> Async.RunSynchronously // start them off
|
||||||
|
|
||||||
// ================================================
|
// ================================================
|
||||||
// .NET compatability
|
// .NET compatibility
|
||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
module NetCompatibilityExamples =
|
module NetCompatibilityExamples =
|
||||||
@ -536,7 +536,7 @@ module NetCompatibilityExamples =
|
|||||||
|
|
||||||
// ------- work with existing library functions -------
|
// ------- work with existing library functions -------
|
||||||
|
|
||||||
let (i1success,i1) = System.Int32.TryParse("123");
|
let (i1success, i1) = System.Int32.TryParse("123");
|
||||||
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
|
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
|
||||||
|
|
||||||
// ------- Implement interfaces on the fly! -------
|
// ------- Implement interfaces on the fly! -------
|
||||||
@ -570,12 +570,12 @@ module NetCompatibilityExamples =
|
|||||||
// abstract base class with virtual methods
|
// abstract base class with virtual methods
|
||||||
[<AbstractClass>]
|
[<AbstractClass>]
|
||||||
type Shape() =
|
type Shape() =
|
||||||
//readonly properties
|
// readonly properties
|
||||||
abstract member Width : int with get
|
abstract member Width : int with get
|
||||||
abstract member Height : int with get
|
abstract member Height : int with get
|
||||||
//non-virtual method
|
// non-virtual method
|
||||||
member this.BoundingArea = this.Height * this.Width
|
member this.BoundingArea = this.Height * this.Width
|
||||||
//virtual method with base implementation
|
// virtual method with base implementation
|
||||||
abstract member Print : unit -> unit
|
abstract member Print : unit -> unit
|
||||||
default this.Print () = printfn "I'm a shape"
|
default this.Print () = printfn "I'm a shape"
|
||||||
|
|
||||||
@ -586,19 +586,19 @@ module NetCompatibilityExamples =
|
|||||||
override this.Height = y
|
override this.Height = y
|
||||||
override this.Print () = printfn "I'm a Rectangle"
|
override this.Print () = printfn "I'm a Rectangle"
|
||||||
|
|
||||||
//test
|
// test
|
||||||
let r = Rectangle(2,3)
|
let r = Rectangle(2, 3)
|
||||||
printfn "The width is %i" r.Width
|
printfn "The width is %i" r.Width
|
||||||
printfn "The area is %i" r.BoundingArea
|
printfn "The area is %i" r.BoundingArea
|
||||||
r.Print()
|
r.Print()
|
||||||
|
|
||||||
// ------- extension methods -------
|
// ------- extension methods -------
|
||||||
|
|
||||||
//Just as in C#, F# can extend existing classes with extension methods.
|
// Just as in C#, F# can extend existing classes with extension methods.
|
||||||
type System.String with
|
type System.String with
|
||||||
member this.StartsWithA = this.StartsWith "A"
|
member this.StartsWithA = this.StartsWith "A"
|
||||||
|
|
||||||
//test
|
// test
|
||||||
let s = "Alice"
|
let s = "Alice"
|
||||||
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
|
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
|
||||||
|
|
||||||
|
@ -6,6 +6,7 @@ contributors:
|
|||||||
- ["Leo Rudberg" , "http://github.com/LOZORD"]
|
- ["Leo Rudberg" , "http://github.com/LOZORD"]
|
||||||
- ["Betsy Lorton" , "http://github.com/schbetsy"]
|
- ["Betsy Lorton" , "http://github.com/schbetsy"]
|
||||||
- ["Bruno Volcov", "http://github.com/volcov"]
|
- ["Bruno Volcov", "http://github.com/volcov"]
|
||||||
|
- ["Andrew Taylor", "http://github.com/andrewjt71"]
|
||||||
filename: LearnGit.txt
|
filename: LearnGit.txt
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -333,6 +334,9 @@ $ git log --oneline
|
|||||||
|
|
||||||
# Show merge commits only
|
# Show merge commits only
|
||||||
$ git log --merges
|
$ git log --merges
|
||||||
|
|
||||||
|
# Show all commits represented by an ASCII graph
|
||||||
|
$ git log --graph
|
||||||
```
|
```
|
||||||
|
|
||||||
### merge
|
### merge
|
||||||
@ -499,6 +503,16 @@ $ git reset 31f2bb1
|
|||||||
# after the specified commit).
|
# after the specified commit).
|
||||||
$ git reset --hard 31f2bb1
|
$ git reset --hard 31f2bb1
|
||||||
```
|
```
|
||||||
|
### revert
|
||||||
|
|
||||||
|
Revert can be used to undo a commit. It should not be confused with reset which restores
|
||||||
|
the state of a project to a previous point. Revert will add a new commit which is the
|
||||||
|
inverse of the specified commit, thus reverting it.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Revert a specified commit
|
||||||
|
$ git revert <commit>
|
||||||
|
```
|
||||||
|
|
||||||
### rm
|
### rm
|
||||||
|
|
||||||
|
@ -108,12 +108,13 @@ can include line breaks.` // Same string type.
|
|||||||
bs := []byte("a slice") // Type conversion syntax.
|
bs := []byte("a slice") // Type conversion syntax.
|
||||||
|
|
||||||
// Because they are dynamic, slices can be appended to on-demand.
|
// Because they are dynamic, slices can be appended to on-demand.
|
||||||
// To append elements to a slice, built-in append() function is used.
|
// To append elements to a slice, the built-in append() function is used.
|
||||||
// First argument is a slice to which we are appending. Commonly,
|
// First argument is a slice to which we are appending. Commonly,
|
||||||
// the array variable is updated in place, as in example below.
|
// the array variable is updated in place, as in example below.
|
||||||
s := []int{1, 2, 3} // Result is a slice of length 3.
|
s := []int{1, 2, 3} // Result is a slice of length 3.
|
||||||
s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
|
s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
|
||||||
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
|
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
|
||||||
|
|
||||||
// To append another slice, instead of list of atomic elements we can
|
// To append another slice, instead of list of atomic elements we can
|
||||||
// pass a reference to a slice or a slice literal like this, with a
|
// pass a reference to a slice or a slice literal like this, with a
|
||||||
// trailing ellipsis, meaning take a slice and unpack its elements,
|
// trailing ellipsis, meaning take a slice and unpack its elements,
|
||||||
|
@ -13,8 +13,8 @@ Groovy - A dynamic language for the Java platform [Read more here.](http://www.g
|
|||||||
/*
|
/*
|
||||||
Set yourself up:
|
Set yourself up:
|
||||||
|
|
||||||
1) Install GVM - http://gvmtool.net/
|
1) Install SDKMAN - http://sdkman.io/
|
||||||
2) Install Groovy: gvm install groovy
|
2) Install Groovy: sdk install groovy
|
||||||
3) Start the groovy console by typing: groovyConsole
|
3) Start the groovy console by typing: groovyConsole
|
||||||
|
|
||||||
*/
|
*/
|
||||||
@ -280,7 +280,7 @@ def clos = { print it }
|
|||||||
clos( "hi" )
|
clos( "hi" )
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Groovy can memorize closure results [1][2][3]
|
Groovy can memoize closure results [1][2][3]
|
||||||
*/
|
*/
|
||||||
def cl = {a, b ->
|
def cl = {a, b ->
|
||||||
sleep(3000) // simulate some time consuming processing
|
sleep(3000) // simulate some time consuming processing
|
||||||
|
@ -81,7 +81,7 @@ not False -- True
|
|||||||
[5,4..1] -- [5, 4, 3, 2, 1]
|
[5,4..1] -- [5, 4, 3, 2, 1]
|
||||||
|
|
||||||
-- indexing into a list
|
-- indexing into a list
|
||||||
[0..] !! 5 -- 5
|
[1..10] !! 3 -- 4
|
||||||
|
|
||||||
-- You can also have infinite lists in Haskell!
|
-- You can also have infinite lists in Haskell!
|
||||||
[1..] -- a list of all the natural numbers
|
[1..] -- a list of all the natural numbers
|
||||||
@ -189,16 +189,16 @@ foo = add 10 -- foo is now a function that takes a number and adds 10 to it
|
|||||||
foo 5 -- 15
|
foo 5 -- 15
|
||||||
|
|
||||||
-- Another way to write the same thing
|
-- Another way to write the same thing
|
||||||
foo = (+10)
|
foo = (10+)
|
||||||
foo 5 -- 15
|
foo 5 -- 15
|
||||||
|
|
||||||
-- function composition
|
-- function composition
|
||||||
-- the (.) function chains functions together.
|
-- the operator `.` chains functions together.
|
||||||
-- For example, here foo is a function that takes a value. It adds 10 to it,
|
-- For example, here foo is a function that takes a value. It adds 10 to it,
|
||||||
-- multiplies the result of that by 4, and then returns the final value.
|
-- multiplies the result of that by 4, and then returns the final value.
|
||||||
foo = (*4) . (+10)
|
foo = (4*) . (10+)
|
||||||
|
|
||||||
-- (5 + 10) * 4 = 60
|
-- 4*(10 + 5) = 60
|
||||||
foo 5 -- 60
|
foo 5 -- 60
|
||||||
|
|
||||||
-- fixing precedence
|
-- fixing precedence
|
||||||
@ -222,7 +222,7 @@ even . fib $ 7 -- false
|
|||||||
-- 5. Type signatures
|
-- 5. Type signatures
|
||||||
----------------------------------------------------
|
----------------------------------------------------
|
||||||
|
|
||||||
-- Haskell has a very strong type system, and everything has a type signature.
|
-- Haskell has a very strong type system, and every valid expression has a type.
|
||||||
|
|
||||||
-- Some basic types:
|
-- Some basic types:
|
||||||
5 :: Integer
|
5 :: Integer
|
||||||
@ -259,7 +259,7 @@ case args of
|
|||||||
_ -> putStrLn "bad args"
|
_ -> putStrLn "bad args"
|
||||||
|
|
||||||
-- Haskell doesn't have loops; it uses recursion instead.
|
-- Haskell doesn't have loops; it uses recursion instead.
|
||||||
-- map applies a function over every element in an array
|
-- map applies a function over every element in a list
|
||||||
|
|
||||||
map (*2) [1..5] -- [2, 4, 6, 8, 10]
|
map (*2) [1..5] -- [2, 4, 6, 8, 10]
|
||||||
|
|
||||||
@ -279,7 +279,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
|
|||||||
-- This is the same as
|
-- This is the same as
|
||||||
(2 * (2 * (2 * 4 + 1) + 2) + 3)
|
(2 * (2 * (2 * 4 + 1) + 2) + 3)
|
||||||
|
|
||||||
-- foldl is left-handed, foldr is right-
|
-- foldl is left-handed, foldr is right-handed
|
||||||
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
|
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
|
||||||
|
|
||||||
-- This is now the same as
|
-- This is now the same as
|
||||||
@ -318,7 +318,7 @@ Nothing -- of type `Maybe a` for any `a`
|
|||||||
-- it is not hard to explain enough to get going.
|
-- it is not hard to explain enough to get going.
|
||||||
|
|
||||||
-- When a Haskell program is executed, `main` is
|
-- When a Haskell program is executed, `main` is
|
||||||
-- called. It must return a value of type `IO ()`. For example:
|
-- called. It must return a value of type `IO a` for some type `a`. For example:
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = putStrLn $ "Hello, sky! " ++ (say Blue)
|
main = putStrLn $ "Hello, sky! " ++ (say Blue)
|
||||||
@ -361,7 +361,7 @@ sayHello = do
|
|||||||
-- You can think of a value of type `IO a` as representing a
|
-- You can think of a value of type `IO a` as representing a
|
||||||
-- computer program that will generate a value of type `a`
|
-- computer program that will generate a value of type `a`
|
||||||
-- when executed (in addition to anything else it does). We can
|
-- when executed (in addition to anything else it does). We can
|
||||||
-- store and reuse this value using `<-`. We can also
|
-- name and reuse this value using `<-`. We can also
|
||||||
-- make our own action of type `IO String`:
|
-- make our own action of type `IO String`:
|
||||||
|
|
||||||
action :: IO String
|
action :: IO String
|
||||||
@ -401,11 +401,26 @@ main'' = do
|
|||||||
|
|
||||||
let foo = 5
|
let foo = 5
|
||||||
|
|
||||||
-- You can see the type of any value with `:t`:
|
-- You can see the type of any value or expression with `:t`:
|
||||||
|
|
||||||
>:t foo
|
> :t foo
|
||||||
foo :: Integer
|
foo :: Integer
|
||||||
|
|
||||||
|
-- Operators, such as `+`, `:` and `$`, are functions.
|
||||||
|
-- Their type can be inspected by putting the operator in parentheses:
|
||||||
|
|
||||||
|
> :t (:)
|
||||||
|
(:) :: a -> [a] -> [a]
|
||||||
|
|
||||||
|
-- You can get additional information on any `name` using `:i`:
|
||||||
|
|
||||||
|
> :i (+)
|
||||||
|
class Num a where
|
||||||
|
(+) :: a -> a -> a
|
||||||
|
...
|
||||||
|
-- Defined in ‘GHC.Num’
|
||||||
|
infixl 6 +
|
||||||
|
|
||||||
-- You can also run any action of type `IO ()`
|
-- You can also run any action of type `IO ()`
|
||||||
|
|
||||||
> sayHello
|
> sayHello
|
||||||
@ -417,7 +432,7 @@ Hello, Friend!
|
|||||||
|
|
||||||
There's a lot more to Haskell, including typeclasses and monads. These are the
|
There's a lot more to Haskell, including typeclasses and monads. These are the
|
||||||
big ideas that make Haskell such fun to code in. I'll leave you with one final
|
big ideas that make Haskell such fun to code in. I'll leave you with one final
|
||||||
Haskell example: an implementation of quicksort in Haskell:
|
Haskell example: an implementation of a quicksort variant in Haskell:
|
||||||
|
|
||||||
```haskell
|
```haskell
|
||||||
qsort [] = []
|
qsort [] = []
|
||||||
@ -426,7 +441,7 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
|
|||||||
greater = filter (>= p) xs
|
greater = filter (>= p) xs
|
||||||
```
|
```
|
||||||
|
|
||||||
Haskell is easy to install. Get it [here](http://www.haskell.org/platform/).
|
There are two popular ways to install Haskell: The traditional [Cabal-based installation](http://www.haskell.org/platform/), and the newer [Stack-based process](https://www.stackage.org/install).
|
||||||
|
|
||||||
You can find a much gentler introduction from the excellent
|
You can find a much gentler introduction from the excellent
|
||||||
[Learn you a Haskell](http://learnyouahaskell.com/) or
|
[Learn you a Haskell](http://learnyouahaskell.com/) or
|
||||||
|
107
hu-hu/coffeescript-hu.html.markdown
Normal file
107
hu-hu/coffeescript-hu.html.markdown
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
---
|
||||||
|
language: coffeescript
|
||||||
|
contributors:
|
||||||
|
- ["Tenor Biel", "http://github.com/L8D"]
|
||||||
|
- ["Xavier Yao", "http://github.com/xavieryao"]
|
||||||
|
translators:
|
||||||
|
- ["Tamás Diószegi", "http://github.com/ditam"]
|
||||||
|
lang: hu-hu
|
||||||
|
filename: coffeescript-hu.coffee
|
||||||
|
---
|
||||||
|
|
||||||
|
A CoffeeScript egy apró nyelv ami egy-az-egyben egyenértékű Javascript kódra fordul, és így futásidőben már nem szükséges interpretálni.
|
||||||
|
Mint a JavaScript egyik követője, a CoffeeScript mindent megtesz azért, hogy olvasható, jól formázott és jól futó JavaScript kódot állítson elő, ami minden JavaScript futtatókörnyezetben jól működik.
|
||||||
|
|
||||||
|
Rézletekért lásd még a [CoffeeScript weboldalát](http://coffeescript.org/), ahol egy teljes CoffeScript tutorial is található.
|
||||||
|
|
||||||
|
```coffeescript
|
||||||
|
# A CoffeeScript egy hipszter nyelv.
|
||||||
|
# Követi több modern nyelv trendjeit.
|
||||||
|
# Így a kommentek, mint Ruby-ban és Python-ban, a szám szimbólummal kezdődnek.
|
||||||
|
|
||||||
|
###
|
||||||
|
A komment blokkok ilyenek, és közvetlenül '/ *' és '* /' jelekre fordítódnak
|
||||||
|
az eredményül kapott JavaScript kódban.
|
||||||
|
|
||||||
|
Mielőtt tovább olvasol, jobb, ha a JavaScript alapvető szemantikájával
|
||||||
|
tisztában vagy.
|
||||||
|
|
||||||
|
(A kód példák alatt kommentként látható a fordítás után kapott JavaScript kód.)
|
||||||
|
###
|
||||||
|
|
||||||
|
# Értékadás:
|
||||||
|
number = 42 #=> var number = 42;
|
||||||
|
opposite = true #=> var opposite = true;
|
||||||
|
|
||||||
|
# Feltételes utasítások:
|
||||||
|
number = -42 if opposite #=> if(opposite) { number = -42; }
|
||||||
|
|
||||||
|
# Függvények:
|
||||||
|
square = (x) -> x * x #=> var square = function(x) { return x * x; }
|
||||||
|
|
||||||
|
fill = (container, liquid = "coffee") ->
|
||||||
|
"Filling the #{container} with #{liquid}..."
|
||||||
|
#=>var fill;
|
||||||
|
#
|
||||||
|
#fill = function(container, liquid) {
|
||||||
|
# if (liquid == null) {
|
||||||
|
# liquid = "coffee";
|
||||||
|
# }
|
||||||
|
# return "Filling the " + container + " with " + liquid + "...";
|
||||||
|
#};
|
||||||
|
|
||||||
|
# Szám tartományok:
|
||||||
|
list = [1..5] #=> var list = [1, 2, 3, 4, 5];
|
||||||
|
|
||||||
|
# Objektumok:
|
||||||
|
math =
|
||||||
|
root: Math.sqrt
|
||||||
|
square: square
|
||||||
|
cube: (x) -> x * square x
|
||||||
|
#=> var math = {
|
||||||
|
# "root": Math.sqrt,
|
||||||
|
# "square": square,
|
||||||
|
# "cube": function(x) { return x * square(x); }
|
||||||
|
# };
|
||||||
|
|
||||||
|
# "Splat" jellegű függvény-paraméterek:
|
||||||
|
race = (winner, runners...) ->
|
||||||
|
print winner, runners
|
||||||
|
#=>race = function() {
|
||||||
|
# var runners, winner;
|
||||||
|
# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
|
||||||
|
# return print(winner, runners);
|
||||||
|
# };
|
||||||
|
|
||||||
|
# Létezés-vizsgálat:
|
||||||
|
alert "I knew it!" if elvis?
|
||||||
|
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
|
||||||
|
|
||||||
|
# Tömb értelmezések: (array comprehensions)
|
||||||
|
cubes = (math.cube num for num in list)
|
||||||
|
#=>cubes = (function() {
|
||||||
|
# var _i, _len, _results;
|
||||||
|
# _results = [];
|
||||||
|
# for (_i = 0, _len = list.length; _i < _len; _i++) {
|
||||||
|
# num = list[_i];
|
||||||
|
# _results.push(math.cube(num));
|
||||||
|
# }
|
||||||
|
# return _results;
|
||||||
|
# })();
|
||||||
|
|
||||||
|
foods = ['broccoli', 'spinach', 'chocolate']
|
||||||
|
eat food for food in foods when food isnt 'chocolate'
|
||||||
|
#=>foods = ['broccoli', 'spinach', 'chocolate'];
|
||||||
|
#
|
||||||
|
#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
|
||||||
|
# food = foods[_k];
|
||||||
|
# if (food !== 'chocolate') {
|
||||||
|
# eat(food);
|
||||||
|
# }
|
||||||
|
#}
|
||||||
|
```
|
||||||
|
|
||||||
|
## További források
|
||||||
|
|
||||||
|
- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
|
||||||
|
- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
|
@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
language: ruby
|
language: ruby
|
||||||
lang: hu-hu
|
lang: hu-hu
|
||||||
filenev: learnruby.rb
|
filename: learnruby-hu.rb
|
||||||
contributors:
|
contributors:
|
||||||
- ["David Underwood", "http://theflyingdeveloper.com"]
|
- ["David Underwood", "http://theflyingdeveloper.com"]
|
||||||
- ["Joel Walden", "http://joelwalden.net"]
|
- ["Joel Walden", "http://joelwalden.net"]
|
||||||
@ -13,7 +13,7 @@ contributors:
|
|||||||
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
||||||
- ["Levi Bostian", "https://github.com/levibostian"]
|
- ["Levi Bostian", "https://github.com/levibostian"]
|
||||||
- ["Rahil Momin", "https://github.com/iamrahil"]
|
- ["Rahil Momin", "https://github.com/iamrahil"]
|
||||||
translators:
|
translators:
|
||||||
- ["Zsolt Prontvai", "https://github.com/prozsolt"]
|
- ["Zsolt Prontvai", "https://github.com/prozsolt"]
|
||||||
---
|
---
|
||||||
|
|
147
hu-hu/yaml-hu.html.markdown
Normal file
147
hu-hu/yaml-hu.html.markdown
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
---
|
||||||
|
language: yaml
|
||||||
|
filename: learnyaml-hu.yaml
|
||||||
|
contributors:
|
||||||
|
- ["Adam Brenecki", "https://github.com/adambrenecki"]
|
||||||
|
translators:
|
||||||
|
- ["Tamás Diószegi", "https://github.com/ditam"]
|
||||||
|
lang: hu-hu
|
||||||
|
---
|
||||||
|
|
||||||
|
A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is
|
||||||
|
olvasható és írható legyen emberi szemmel.
|
||||||
|
|
||||||
|
A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt
|
||||||
|
szintaktikai jelentéssel bíró sortörésekkel és indentációval,
|
||||||
|
a Pythonhoz hasonlóan. A Pythonnal ellentétben azonban a YAML nem engedélyezi
|
||||||
|
a közvetlen tab karakterek jelenlétét.
|
||||||
|
|
||||||
|
Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő,
|
||||||
|
a kódolást a tartalomban explicit nem kell (és nem is lehet) feltüntetni.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# A kommentek YAML-ban így néznek ki.
|
||||||
|
|
||||||
|
##################
|
||||||
|
# Skalár típusok #
|
||||||
|
##################
|
||||||
|
|
||||||
|
# A gyökér objektumunk (az egész dokumentumra értve) egy map,
|
||||||
|
# ami a más nyelvekből ismert dictionary, hash vagy object típusokkal egyenértékű.
|
||||||
|
kulcs: érték
|
||||||
|
masik_kulcs: Másik érték jön ide.
|
||||||
|
egy_szam: 100
|
||||||
|
tudomanyos_jelolessel: 1e+12
|
||||||
|
boolean: true
|
||||||
|
null_value: null
|
||||||
|
kulcs benne szóközökkel: érték
|
||||||
|
# Látható, hogy a sztringeket nem szükséges idézőjelek közé zárni, bár szabad.
|
||||||
|
Továbbá: "Idézőjelekkel megadott sztring."
|
||||||
|
"A kulcs is lehet idézőjeles.": "Hasznos lehet, ha ':'-ot akarsz a kulcsban."
|
||||||
|
|
||||||
|
# Többsoros sztringek írhatóak 'literal block'-ként ('|' jelet használva)
|
||||||
|
# vagy 'folded block'-ként is ('>' jelet használva).
|
||||||
|
literal_block: |
|
||||||
|
Ez az egész szöveg-blokk lesz az értéke a literal_block kulcsnak,
|
||||||
|
a sortöréseket megtartva.
|
||||||
|
|
||||||
|
Az ilyen sztringet az indentáció visszahúzása zárja le, a behúzás pedig
|
||||||
|
eltávolításra kerül.
|
||||||
|
|
||||||
|
A 'még jobban' behúzott részek megtartják a behúzásukat -
|
||||||
|
ezeknek a soroknak 4 szóköz behúzása lesz.
|
||||||
|
folded_style: >
|
||||||
|
Az az egész szöveg-blokk lesz az értéke a 'folded_style' kulcsnak, de
|
||||||
|
ezúttal minden sortörés egy szóközre lesz cserélve.
|
||||||
|
|
||||||
|
Az üres sorok, mint a fenti, új sor karakterre cserélődnek.
|
||||||
|
|
||||||
|
A 'még jobban' behúzott sorok megtartják a sortöréseiket, -
|
||||||
|
ez a szöveg két sorban jelenik meg.
|
||||||
|
|
||||||
|
######################
|
||||||
|
# Gyűjtemény típusok #
|
||||||
|
######################
|
||||||
|
|
||||||
|
# Egymásba ágyazás a behúzás változtatásával érhető el.
|
||||||
|
beagyazott_map:
|
||||||
|
key: value
|
||||||
|
another_key: Another Value
|
||||||
|
masik_beagyazott_map:
|
||||||
|
hello: hello
|
||||||
|
|
||||||
|
# A mapeknek nem csak sztring kulcsaik lehetnek.
|
||||||
|
0.25: lebegőpontos kulcs
|
||||||
|
|
||||||
|
# A kulcsok lehetnek többsoros objektumok is, ? jellel jelezve a kulcs kezdetét
|
||||||
|
? |
|
||||||
|
Ez itt egy
|
||||||
|
többsoros kulcs
|
||||||
|
: és ez az értéke
|
||||||
|
|
||||||
|
# Szintén engedélyezett a kollekció típusok használata kulcsként, de egyéb
|
||||||
|
# nyelvekben ez gyakran problémákat fog okozni.
|
||||||
|
|
||||||
|
# Szekvenciák (listákkal vagy tömbökkel egyenértékűek) így néznek ki:
|
||||||
|
egy_szekvencia:
|
||||||
|
- Item 1
|
||||||
|
- Item 2
|
||||||
|
- 0.5 # Többféle típust is tartalmazhat
|
||||||
|
- Item 4
|
||||||
|
- key: value
|
||||||
|
another_key: another_value
|
||||||
|
-
|
||||||
|
- Ez egy szekvencia
|
||||||
|
- egy másik szekvenciába ágyazva
|
||||||
|
|
||||||
|
# Mivel a YAML a JSON befoglaló halmazát alkotja, JSON szintaxisú
|
||||||
|
# mapek és szekvenciák is használhatóak:
|
||||||
|
json_map: {"key": "value"}
|
||||||
|
json_seq: [3, 2, 1, "takeoff"]
|
||||||
|
|
||||||
|
#########################
|
||||||
|
# EXTRA YAML KÉPESSÉGEK #
|
||||||
|
#########################
|
||||||
|
|
||||||
|
# A YAML-ben ún. 'anchor'-ök segítségével könnyen lehet duplikálni
|
||||||
|
# tartalmakat a dokumentumon belül. A következő kulcsok azonos értékkel bírnak:
|
||||||
|
anchored_tartalom: &anchor_neve Ez a sztring két kulcs értéke is lesz.
|
||||||
|
másik_anchor: *anchor_neve
|
||||||
|
|
||||||
|
# Vannak a YAML-ben tagek is, amivel explicit lehet típusokat jelölni.
|
||||||
|
explicit_string: !!str 0.5
|
||||||
|
# Bizonyos implementációk nyelv-specifikus tageket tartalmaznak, mint
|
||||||
|
# például ez a Python komplex szám típusának jelölésére:
|
||||||
|
python_complex_number: !!python/complex 1+2j
|
||||||
|
|
||||||
|
######################
|
||||||
|
# EXTRA YAML TÍPUSOK #
|
||||||
|
######################
|
||||||
|
|
||||||
|
# Nem a sztringek és a számok az egyedüli skalár típusok YAML-ben.
|
||||||
|
# ISO-formátumú dátumok és dátumot jelölő literal kifejezések is értelmezettek.
|
||||||
|
datetime: 2001-12-15T02:59:43.1Z
|
||||||
|
datetime_with_spaces: 2001-12-14 21:59:43.10 -5
|
||||||
|
date: 2002-12-14
|
||||||
|
|
||||||
|
# A !!binary tag jelöli, hogy egy sztring valójában base64-kódolású
|
||||||
|
# reprezentációja egy bináris blob-nak
|
||||||
|
gif_file: !!binary |
|
||||||
|
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
|
||||||
|
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
|
||||||
|
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
|
||||||
|
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
|
||||||
|
|
||||||
|
# Létezik a YAML-ban egy halmaz típus (set) is, ami így néz ki:
|
||||||
|
set:
|
||||||
|
? elem1
|
||||||
|
? elem2
|
||||||
|
? elem3
|
||||||
|
|
||||||
|
# Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti
|
||||||
|
# halmaz egyenértékű a következővel:
|
||||||
|
set2:
|
||||||
|
elem1: null
|
||||||
|
elem2: null
|
||||||
|
elem3: null
|
||||||
|
```
|
848
id-id/php-id.html.markdown
Normal file
848
id-id/php-id.html.markdown
Normal file
@ -0,0 +1,848 @@
|
|||||||
|
---
|
||||||
|
language: PHP
|
||||||
|
contributors:
|
||||||
|
- ["Malcolm Fell", "http://emarref.net/"]
|
||||||
|
- ["Trismegiste", "https://github.com/Trismegiste"]
|
||||||
|
filename: learnphp-id.php
|
||||||
|
translators:
|
||||||
|
- ["Ahmad Zafrullah", "https://github.com/23Pstars"]
|
||||||
|
lang: id-id
|
||||||
|
---
|
||||||
|
|
||||||
|
Dokumen ini menjelaskan tentang PHP5 keatas.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php // Skrip PHP harus diawali dengan tag <?php
|
||||||
|
|
||||||
|
// Jika dokumen PHP hanya mengandung kode PHP, sebaiknya tidak menggunakan
|
||||||
|
// tag penutup PHP untuk menghindari ketidaksengajaan tampilnya sesuatu.
|
||||||
|
|
||||||
|
// Dua garis miring diawal digunakan untuk komentar satu baris.
|
||||||
|
|
||||||
|
/*
|
||||||
|
Membatasi teks dalam garis miring-bintang dan bintang-garis miring
|
||||||
|
membuat komentar untuk banyak-baris sekaligus.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Gunakan "echo" or "print" untuk menampilkan sesuatu
|
||||||
|
print('Halo '); // Menampilkan "Halo " tanpa baris baru
|
||||||
|
|
||||||
|
// () boleh tidak digunakan dalam menggunakan "print" dan "echo"
|
||||||
|
echo "Dunia\n"; // Menampilkan "Dunia" dengan baris baru
|
||||||
|
// (semua perintah harus diakhiri dengan titik koma)
|
||||||
|
|
||||||
|
// Apapun yang berada diluar tag <?php akan ditampilkan secara otomatis
|
||||||
|
?>
|
||||||
|
Halo Dunia, lagi!
|
||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
/************************************
|
||||||
|
* Tipe Data & Variabel
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Variabel diawali dengan simnbol $.
|
||||||
|
// Nama variabel yang benar diawali dengan huruf atau garis-bawah,
|
||||||
|
// diikuti dengan beberapa huruf, angka, dan garis-bawah lainnya.
|
||||||
|
|
||||||
|
// Nilai Boolean adalah case-insensitive
|
||||||
|
$boolean = true; // atau TRUE atau True
|
||||||
|
$boolean = false; // atau FALSE atau False
|
||||||
|
|
||||||
|
// Nilai Integer
|
||||||
|
$int1 = 12; // => 12
|
||||||
|
$int2 = -12; // => -12
|
||||||
|
$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal)
|
||||||
|
$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal)
|
||||||
|
// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0.
|
||||||
|
$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner)
|
||||||
|
|
||||||
|
// Nilai Floats (dikenal juga sebagai Doubles)
|
||||||
|
$float = 1.234;
|
||||||
|
$float = 1.2e3;
|
||||||
|
$float = 7E-10;
|
||||||
|
|
||||||
|
// Menghapus variable
|
||||||
|
unset($int1);
|
||||||
|
|
||||||
|
// Aritmatika
|
||||||
|
$jumlah = 1 + 1; // 2
|
||||||
|
$selisih = 2 - 1; // 1
|
||||||
|
$perkalian = 2 * 2; // 4
|
||||||
|
$pembagian = 2 / 1; // 2
|
||||||
|
|
||||||
|
// Aritmatika singkat
|
||||||
|
$angka = 0;
|
||||||
|
$angka += 1; // Menjumlahkan $angka dengan 1
|
||||||
|
echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan)
|
||||||
|
echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan)
|
||||||
|
$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka;
|
||||||
|
|
||||||
|
// String biasanya diawali dan ditutup dengan petik satu.
|
||||||
|
$sgl_quotes = '$String'; // => '$String'
|
||||||
|
|
||||||
|
// Hindari menggunakan petik dua kecuali menyertakan variabel lain
|
||||||
|
$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.'
|
||||||
|
|
||||||
|
// Karakter khusus hanya berlaku pada petik dua
|
||||||
|
$berfungsi = "Ini mengandung \t karakter tab.";
|
||||||
|
$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t';
|
||||||
|
|
||||||
|
// Batasi variabel dengan kurung kurawal jika diperlukan
|
||||||
|
$uang = "Saya memiliki $${angka} di Bank.";
|
||||||
|
|
||||||
|
// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris
|
||||||
|
$nowdoc = <<<'END'
|
||||||
|
Banyak baris
|
||||||
|
string
|
||||||
|
END;
|
||||||
|
|
||||||
|
// Heredocs akan melakukan interpolasi
|
||||||
|
$heredoc = <<<END
|
||||||
|
Banyak baris
|
||||||
|
$sgl_quotes
|
||||||
|
END;
|
||||||
|
|
||||||
|
// Menyambung string dapat dilakukan menggunakan .
|
||||||
|
echo 'String ini ' . 'tersambung';
|
||||||
|
|
||||||
|
// String dapat dijadikan parameter pada "echo"
|
||||||
|
echo 'Banyak', 'Parameter', 'String'; // Menampilkan 'BanyakParameterString'
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Konstan
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Sebuah konstan didifinisikan menggunakan fungsi define()
|
||||||
|
// dan tidak bisa diganti/rubah selama program berjalan!
|
||||||
|
|
||||||
|
// Nama konstan yang benar diawali dengan huruf dan garis-bawah,
|
||||||
|
// diikuti dengan beberapa huruf, angka, atau garis-bawah.
|
||||||
|
define("FOO", "sesuatu");
|
||||||
|
|
||||||
|
// Mengakses konstan memungkinkan untuk dapat dipanggil tanpa menggunakan simbol $
|
||||||
|
echo FOO; // Menampilkan 'sesuatu'
|
||||||
|
echo 'Keluaran ini adalah ' . FOO; // Menampilkan 'Keluaran ini adalah sesuatu'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Larik (Array)
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Semua larik dalam PHP bersifat asosiatif (saling berhubungan).
|
||||||
|
|
||||||
|
// Berfungsi pada semua versi PHP
|
||||||
|
$asosiatif = array('Satu' => 1, 'Dua' => 2, 'Tiga' => 3);
|
||||||
|
|
||||||
|
// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru
|
||||||
|
$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3];
|
||||||
|
|
||||||
|
echo $asosiatif['Satu']; // menampilkan 1
|
||||||
|
|
||||||
|
// Daftar literal secara tidak langsung ditentukan oleh kunci integer
|
||||||
|
$larik = ['Satu', 'Dua', 'Tiga'];
|
||||||
|
echo $larik[0]; // => "Satu"
|
||||||
|
|
||||||
|
// Menambahkan sebuah elemen pada akhir larik
|
||||||
|
$larik[] = 'Empat';
|
||||||
|
// atau
|
||||||
|
array_push($larik, 'Lima');
|
||||||
|
|
||||||
|
// Menghapus elemen dari larik
|
||||||
|
unset($larik[3]);
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Keluaran
|
||||||
|
*/
|
||||||
|
|
||||||
|
echo('Halo Dunia!');
|
||||||
|
// Menampilkan Halo Dunia! ke "stdout".
|
||||||
|
// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser).
|
||||||
|
|
||||||
|
print('Halo Dunia!'); // Sama seperti "echo"
|
||||||
|
|
||||||
|
// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan
|
||||||
|
echo 'Halo Dunia!';
|
||||||
|
print 'Halo Dunia!';
|
||||||
|
|
||||||
|
$paragraf = 'paragraf';
|
||||||
|
|
||||||
|
echo 100; // Menampilkan variabel skalar secara langsung
|
||||||
|
echo $paragraf; // atau sebuat variabel
|
||||||
|
|
||||||
|
// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan
|
||||||
|
// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat
|
||||||
|
|
||||||
|
?>
|
||||||
|
<p><?= $paragraf ?></p>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$x = 1;
|
||||||
|
$y = 2;
|
||||||
|
$x = $y; // $x sekarang berisi nilai yang sama dengan $y
|
||||||
|
$z = &$y;
|
||||||
|
// $z sekarang berisi referensi ke $y. Mengubah nilai dari $z
|
||||||
|
// akan mengubah nilai dari $y juga, begitupun sebaliknya.
|
||||||
|
// $x tetap tidak berubah sebagaimana nilai asli dari $y
|
||||||
|
|
||||||
|
echo $x; // => 2
|
||||||
|
echo $z; // => 2
|
||||||
|
$y = 0;
|
||||||
|
echo $x; // => 2
|
||||||
|
echo $z; // => 0
|
||||||
|
|
||||||
|
// Menampilkan tipe dan nilai dari variabel ke "stdout"
|
||||||
|
var_dump($z); // prints int(0)
|
||||||
|
|
||||||
|
// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca
|
||||||
|
print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga )
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Logika
|
||||||
|
*/
|
||||||
|
$a = 0;
|
||||||
|
$b = '0';
|
||||||
|
$c = '1';
|
||||||
|
$d = '1';
|
||||||
|
|
||||||
|
// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar
|
||||||
|
|
||||||
|
// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda.
|
||||||
|
assert($a == $b); // kesamaan
|
||||||
|
assert($c != $a); // ketidak-samaan
|
||||||
|
assert($c <> $a); // versi lain dari ketidak-samaan
|
||||||
|
assert($a < $c);
|
||||||
|
assert($c > $b);
|
||||||
|
assert($a <= $b);
|
||||||
|
assert($c >= $d);
|
||||||
|
|
||||||
|
// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama.
|
||||||
|
assert($c === $d);
|
||||||
|
assert($a !== $d);
|
||||||
|
assert(1 === '1');
|
||||||
|
assert(1 !== '1');
|
||||||
|
|
||||||
|
// Operator 'Spaceship' (sejak PHP 7)
|
||||||
|
// Mengembalikan 0 jika nilai pada kedua sisi adalah sama
|
||||||
|
// Mengembalikan 1 jika nilai pada sisi kiri lebih besar
|
||||||
|
// Mengembalikan -1 jika nilai pada sisi kanan lebih besar
|
||||||
|
|
||||||
|
$a = 100;
|
||||||
|
$b = 1000;
|
||||||
|
|
||||||
|
echo $a <=> $a; // 0 karena keduanya sama
|
||||||
|
echo $a <=> $b; // -1 karena $a < $b
|
||||||
|
echo $b <=> $a; // 1 karena $b > $a
|
||||||
|
|
||||||
|
// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya.
|
||||||
|
|
||||||
|
$integer = 1;
|
||||||
|
echo $integer + $integer; // => 2
|
||||||
|
|
||||||
|
$string = '1';
|
||||||
|
echo $string + $string; // => 2 (string dipaksa menjadi integer)
|
||||||
|
|
||||||
|
$string = 'satu';
|
||||||
|
echo $string + $string; // => 0
|
||||||
|
// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer
|
||||||
|
|
||||||
|
// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya
|
||||||
|
|
||||||
|
$boolean = (boolean) 1; // => true
|
||||||
|
|
||||||
|
$nol = 0;
|
||||||
|
$boolean = (boolean) $nol; // => false
|
||||||
|
|
||||||
|
// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe
|
||||||
|
$integer = 5;
|
||||||
|
$string = strval($integer);
|
||||||
|
|
||||||
|
$var = null; // Nilai Null
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Struktur Kontrol
|
||||||
|
*/
|
||||||
|
|
||||||
|
if (true) {
|
||||||
|
print 'Saya tampil';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false) {
|
||||||
|
print 'Saya tidak tampil';
|
||||||
|
} else {
|
||||||
|
print 'Saya tampil';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false) {
|
||||||
|
print 'Tidak tampil';
|
||||||
|
} elseif(true) {
|
||||||
|
print 'Tampil';
|
||||||
|
}
|
||||||
|
|
||||||
|
// operator ternary
|
||||||
|
print (false ? 'Tidak tampil' : 'Tampil');
|
||||||
|
|
||||||
|
// cara pintas operator ternary mulai dirilis sejak PHP 5.3
|
||||||
|
// persamaan dari "$x ? $x : 'Kerjakan'"
|
||||||
|
$x = false;
|
||||||
|
print($x ?: 'Kerjakan');
|
||||||
|
|
||||||
|
// operator null coalesce sejak PHP 7
|
||||||
|
$a = null;
|
||||||
|
$b = 'Ditampilkan';
|
||||||
|
echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set'
|
||||||
|
echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan'
|
||||||
|
|
||||||
|
|
||||||
|
$x = 0;
|
||||||
|
if ($x === '0') {
|
||||||
|
print 'Tidak ditampilkan';
|
||||||
|
} elseif($x == '1') {
|
||||||
|
print 'Tidak ditampilkan';
|
||||||
|
} else {
|
||||||
|
print 'Tampil';
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Alternatif sintaks untuk kebutuhan templat:
|
||||||
|
?>
|
||||||
|
|
||||||
|
<?php if ($x): ?>
|
||||||
|
Ini ditampilkan jika pengujian benar.
|
||||||
|
<?php else: ?>
|
||||||
|
Selain tersebut ini yang akan ditampilkan.
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Gunakan "switch" untuk menghemat logika.
|
||||||
|
switch ($x) {
|
||||||
|
case '0':
|
||||||
|
print 'Switch mendukung tipe paksaan';
|
||||||
|
break; // Kata kunci "break" harus disertakan, jika tidak
|
||||||
|
// maka logika tersebut akan berlanjut ke bagian "dua" dan "tiga"
|
||||||
|
case 'dua':
|
||||||
|
case 'tiga':
|
||||||
|
// Lakukan sesuatu jika $x bernilai "dua" atau "tiga"
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// Aksi cadangan
|
||||||
|
}
|
||||||
|
|
||||||
|
// "while", "do...while" dan perulangan "for"
|
||||||
|
$i = 0;
|
||||||
|
while ($i < 5) {
|
||||||
|
echo $i++;
|
||||||
|
}; // Menampilkan "01234"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$i = 0;
|
||||||
|
do {
|
||||||
|
echo $i++;
|
||||||
|
} while ($i < 5); // Menampilkan "01234"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
for ($x = 0; $x < 10; $x++) {
|
||||||
|
echo $x;
|
||||||
|
} // Menampilkan "0123456789"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$roda = ['sepeda' => 2, 'mobil' => 4];
|
||||||
|
|
||||||
|
// Perulangan "foreach" dapat melakukan iterasi pada larik (array)
|
||||||
|
foreach ($roda as $jumlah_roda) {
|
||||||
|
echo $jumlah_roda;
|
||||||
|
} // Menampilkan "24"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai)
|
||||||
|
foreach ($roda as $mesin => $jumlah_roda) {
|
||||||
|
echo "$mesin memiliki $jumlah_roda buah roda";
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$i = 0;
|
||||||
|
while ($i < 5) {
|
||||||
|
if ($i === 3) {
|
||||||
|
break; // Menghentikan proses perulangan
|
||||||
|
}
|
||||||
|
echo $i++;
|
||||||
|
} // Menampilkan "012"
|
||||||
|
|
||||||
|
for ($i = 0; $i < 5; $i++) {
|
||||||
|
if ($i === 3) {
|
||||||
|
continue; // Melewati tahapan iterasi saat ini
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
} // Menampilkan "0124"
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Fungsi
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Fungsi didefinisikan dengan "function":
|
||||||
|
function fungsi_saya () {
|
||||||
|
return 'Halo';
|
||||||
|
}
|
||||||
|
|
||||||
|
echo fungsi_saya(); // => "Halo"
|
||||||
|
|
||||||
|
// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh
|
||||||
|
// beberapa huruf, angka, atau garis-bawah.
|
||||||
|
|
||||||
|
function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1
|
||||||
|
$hasil = $x + $y;
|
||||||
|
return $hasil;
|
||||||
|
}
|
||||||
|
|
||||||
|
echo jumlah(4); // => 5
|
||||||
|
echo jumlah(4, 2); // => 6
|
||||||
|
|
||||||
|
// $hasil tidak dapat diakses dari luar fungsi
|
||||||
|
// print $hasil; // Akan menghasilkan sebuah "warning".
|
||||||
|
|
||||||
|
// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous);
|
||||||
|
$inc = function ($x) {
|
||||||
|
return $x + 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
echo $inc(2); // => 3
|
||||||
|
|
||||||
|
function foo ($x, $y, $z) {
|
||||||
|
echo "$x - $y - $z";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fungsi dapat mengembalikan fungsi juga
|
||||||
|
function bar ($x, $y) {
|
||||||
|
// Gunakan "use" untuk mengakses variabel diluar fungsi
|
||||||
|
return function ($z) use ($x, $y) {
|
||||||
|
foo($x, $y, $z);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$bar = bar('A', 'B');
|
||||||
|
$bar('C'); // Menampilkan "A - B - C"
|
||||||
|
|
||||||
|
// Fungsi uang memiliki nama dapat dipanggil berdasarkan string
|
||||||
|
$nama_fungsi = 'jumlah';
|
||||||
|
echo $nama_fungsi(1, 2); // => 3
|
||||||
|
// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis.
|
||||||
|
// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]);
|
||||||
|
|
||||||
|
// Akses semua parameter yang dikirim ke sebuah fungsi
|
||||||
|
function parameter() {
|
||||||
|
$jumlah_param = func_num_args();
|
||||||
|
if( $jumlah_param > 0 ) {
|
||||||
|
echo func_get_arg(0) . ' | ';
|
||||||
|
}
|
||||||
|
$daftar_param = func_get_args();
|
||||||
|
foreach( $daftar_param as $kunci => $param ) {
|
||||||
|
echo $kunci . ' - ' . $param . ' | ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia |
|
||||||
|
|
||||||
|
// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter
|
||||||
|
function variabel($kata, ...$daftar) {
|
||||||
|
echo $kata . " || ";
|
||||||
|
foreach ($daftar as $item) {
|
||||||
|
echo $item . ' | ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia |
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Penyertaan ("include")
|
||||||
|
*/
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// Skrip PHP yang berada dalam dokumen "include" juga harus dibuka dengan tag PHP.
|
||||||
|
|
||||||
|
include 'dokumen-saya.php';
|
||||||
|
// Kode yang ada dalam dokumen-saya.php sekarang dapat diakses dari cakupan saat ini.
|
||||||
|
// Jika dokumen tidak dapat disertakan (include, seperti dokumen tidak ditemukan), maka pesan peringatan akan muncul.
|
||||||
|
|
||||||
|
include_once 'dokumen-saya.php';
|
||||||
|
// Jika dokumen-saya telah disertakan (include) oleh perintah sebelumnya, maka
|
||||||
|
// dokumen tersebut tidak akan disertakan lagi. Ini bertujuan untuk menghindari kesalahan
|
||||||
|
// yang diakibatkan oleh deklarasi ganda.
|
||||||
|
|
||||||
|
require 'dokumen-saya.php';
|
||||||
|
require_once 'dokumen-saya.php';
|
||||||
|
// Memiliki fungsi yang sama dengan "include", namun jika dokumen tidak ditemukan
|
||||||
|
// atau tidak dapat disertakan maka akan menghasilkan pesan kesalahan fatal.
|
||||||
|
|
||||||
|
// Isi dari dokumen-saya.php:
|
||||||
|
<?php
|
||||||
|
|
||||||
|
return 'Apapun yang kamu suka.';
|
||||||
|
// akhir dari dokumen
|
||||||
|
|
||||||
|
// "include" dan "require" dapat mengembalikan sebuah nilai.
|
||||||
|
$nilai = include 'dokumen-saya.php';
|
||||||
|
|
||||||
|
// Dokumen akan disertakan berdasarkan lokasi direktori dokumen (file path) yang diberikan, jika tidak didefinisikan
|
||||||
|
// maka akan digunakan konfigurasi dari "include_path". Jika dokumen tidak ditemukan dalam "include_path",
|
||||||
|
// fungsi include akan melakukan pengecekan pada direktori yang sama dengan dokumen yang menggunakan fungsi include tersebut,
|
||||||
|
// jika tidak ditemukan juga maka pesan gagal akan dimunculkan.
|
||||||
|
/* */
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Kelas (class)
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Kelas didefinisikan dengan kata "class"
|
||||||
|
|
||||||
|
class KelasSaya
|
||||||
|
{
|
||||||
|
const NILAI_KONSTAN = 'nilai'; // Sebuah konstan
|
||||||
|
|
||||||
|
static $nilaiStatis = 'statis';
|
||||||
|
|
||||||
|
// Variabel statis dan hak jenis aksesnya
|
||||||
|
public static $variabelStatisPublik = 'nilaiStatisPublik';
|
||||||
|
// Hanya dapat diakses dalam kelas
|
||||||
|
private static $variabelStatisPrivat = 'nilaiStatisPrivat';
|
||||||
|
// Dapat diakses dalam kelas dan kelas turunan
|
||||||
|
protected static $variabelStatisTerlindungi = 'nilaiStatisTerlindungi';
|
||||||
|
|
||||||
|
// Properti harus mendeklarasikan hak aksesnya
|
||||||
|
public $properti = 'publik';
|
||||||
|
public $PropertiInstansi;
|
||||||
|
protected $variabel = 'terlindungi'; // Dapat diakses dari kelas itu sendiri dan kelas turunannya
|
||||||
|
private $variabel = 'tersembunyi'; // Hanya dapat diakses dari kelas itu sendiri
|
||||||
|
|
||||||
|
// Membuat konstruktor dengan perintah __construct
|
||||||
|
public function __construct($PropertiInstansi) {
|
||||||
|
// Akses variabel instansi menggunakan perintah $this
|
||||||
|
$this->PropertiInstansi = $PropertiInstansi;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method dideklarasikan sebagai fungsi didalam kelas
|
||||||
|
public function methodSaya()
|
||||||
|
{
|
||||||
|
print 'KelasSaya';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya
|
||||||
|
final function tidakDapatDiOverride()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut
|
||||||
|
* dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui
|
||||||
|
* objek kelas yang hasil instansiasi, sedangkan method statis bisa.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public static function methodStatisSaya()
|
||||||
|
{
|
||||||
|
print 'Saya adalah statis';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Konstan pada kelas dapat diakses secara statis
|
||||||
|
echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai'
|
||||||
|
|
||||||
|
echo KelasSaya::$nilaiStatis; // Menampilkan 'statis'
|
||||||
|
KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis'
|
||||||
|
|
||||||
|
// Instansi kelas menggunakan perintah "new"
|
||||||
|
$kelas_saya = new KelasSaya('Sebuah properti instansiasi');
|
||||||
|
// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen.
|
||||||
|
|
||||||
|
// Akses anggota kelas menggunakan ->
|
||||||
|
echo $kelas_saya->properti; // => "publik"
|
||||||
|
echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi"
|
||||||
|
$kelas_saya->methodSaya(); // => "KelasSaya"
|
||||||
|
|
||||||
|
// Menurunkan kelas menggunakan kata kunci "extends"
|
||||||
|
class KelasSayaLainnya extends KelasSaya
|
||||||
|
{
|
||||||
|
function tampilkanPropertiTerlindungi()
|
||||||
|
{
|
||||||
|
echo $this->properti;
|
||||||
|
}
|
||||||
|
|
||||||
|
// "override" terhadap sebuah method
|
||||||
|
function methodSaya()
|
||||||
|
{
|
||||||
|
parent::methodSaya();
|
||||||
|
print ' > KelasSayaLainnya';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti');
|
||||||
|
$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi"
|
||||||
|
$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya"
|
||||||
|
|
||||||
|
final class SayaTidakBisaDiturunkan
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters"
|
||||||
|
class PetaKelasSaya
|
||||||
|
{
|
||||||
|
private $properti;
|
||||||
|
|
||||||
|
public function __get($key)
|
||||||
|
{
|
||||||
|
return $this->$key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __set($key, $value)
|
||||||
|
{
|
||||||
|
$this->$key = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$x = new PetaKelasSaya();
|
||||||
|
echo $x->properti; // akan memanggil method __get()
|
||||||
|
$x->properti = 'Sesuatu'; // akan memanggil method __set();
|
||||||
|
|
||||||
|
// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau
|
||||||
|
// meng-implementasikan interfaces (menggunakan kata kunci "implements").
|
||||||
|
// Sebuah interface dideklarasikan dengan perintah "interface".
|
||||||
|
|
||||||
|
interface InterfaceSatu
|
||||||
|
{
|
||||||
|
public function kerjakanSesuatu();
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InterfaceDua
|
||||||
|
{
|
||||||
|
public function kerjakanYangLain();
|
||||||
|
}
|
||||||
|
|
||||||
|
// interface dapat diturunkan
|
||||||
|
interface InterfaceTiga extends InterfaceDua
|
||||||
|
{
|
||||||
|
public function kerjakanYangBerbeda();
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class KelasAbstrakSaya implements InterfaceSatu
|
||||||
|
{
|
||||||
|
public $x = 'kerjakanSesuatu';
|
||||||
|
}
|
||||||
|
|
||||||
|
class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo
|
||||||
|
{
|
||||||
|
public function kerjakanSesuatu()
|
||||||
|
{
|
||||||
|
echo $x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function kerjakanYangLain()
|
||||||
|
{
|
||||||
|
echo 'kerjakanYangLain';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kelas dapat diimplementasikan pada banyak interface
|
||||||
|
class KelasLainnya implements InterfaceSatu, InterfaceDua
|
||||||
|
{
|
||||||
|
public function kerjakanSesuatu()
|
||||||
|
{
|
||||||
|
echo 'kerjakanSesuatu';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function kerjakanYangLain()
|
||||||
|
{
|
||||||
|
echo 'kerjakanYangLain';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Sifat (Traits)
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait"
|
||||||
|
|
||||||
|
trait TraitSaya
|
||||||
|
{
|
||||||
|
public function methodTraitSaya()
|
||||||
|
{
|
||||||
|
print 'Saya menggunakan Trait';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class KelasTraitSaya
|
||||||
|
{
|
||||||
|
use TraitSaya;
|
||||||
|
}
|
||||||
|
|
||||||
|
$kls = new KelasTraitSaya();
|
||||||
|
$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait"
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* Namespaces
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Bagian ini telah dibatasi, karena deklarasi "namespace"
|
||||||
|
// karena harus ditempatkan diawal dokumen.
|
||||||
|
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Secara default, kelas tersedia sebagai namespace umum, dan dapat
|
||||||
|
// secara khusus dipanggil dengan garis-miring terbalik (backslash).
|
||||||
|
|
||||||
|
$kls = new \KelasSaya();
|
||||||
|
|
||||||
|
|
||||||
|
// Menentukan namespace untuk sebuah dokumen
|
||||||
|
namespace Saya\Namespace;
|
||||||
|
|
||||||
|
class KelasSaya
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// (dari dokumen lainnya)
|
||||||
|
$kls = new Saya\Namespace\KelasSaya;
|
||||||
|
|
||||||
|
// Atau dari dalam namespace lainnya.
|
||||||
|
namespace Saya\Lainnya\Namespace;
|
||||||
|
|
||||||
|
use Saya\Namespace\KelasSaya;
|
||||||
|
|
||||||
|
$kls = new KelasSaya();
|
||||||
|
|
||||||
|
// Namespace dapat menggunakan alias
|
||||||
|
|
||||||
|
namespace Saya\Lainnya\Namespace;
|
||||||
|
|
||||||
|
use Saya\Namespace as SuatuKelasLainnya;
|
||||||
|
|
||||||
|
$kls = new SuatuKelasLainnya\KelasSaya();
|
||||||
|
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* Late Static Binding
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
class KelasInduk {
|
||||||
|
public static function siapa() {
|
||||||
|
echo "Ini adalah " . __CLASS__ . "\n";
|
||||||
|
}
|
||||||
|
public static function coba() {
|
||||||
|
// kata kunci "self" merujuk pada method yang berada dalam satu kelas
|
||||||
|
self::who();
|
||||||
|
// kata kunci "static" merujuk pada method yang berada di kelas dimana method itu dijalankan
|
||||||
|
static::who();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
KelasInduk::coba();
|
||||||
|
/*
|
||||||
|
Ini adalah KelasInduk
|
||||||
|
Ini adalah KelasInduk
|
||||||
|
*/
|
||||||
|
|
||||||
|
class KelasAnak extends KelasInduk {
|
||||||
|
public static function siapa() {
|
||||||
|
echo "Tapi ini adalah " . __CLASS__ . "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
KelasAnak::tes();
|
||||||
|
/*
|
||||||
|
Ini adalah KelasInduk
|
||||||
|
Tapi ini adalah KelasAnak
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* Magic constants
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Mendapatkan nama dari suatu kelas. Harus dideklarasikan didalam kelas tersebut.
|
||||||
|
echo "Nama kelas ini adalah " . __CLASS__;
|
||||||
|
|
||||||
|
// Mendapatkan alamat lengkap direktori
|
||||||
|
echo "Alamat direktori ini adalah " . __DIR__;
|
||||||
|
|
||||||
|
// Beberapa yang banyak digunakan
|
||||||
|
require __DIR__ . '/vendor/autoload.php';
|
||||||
|
|
||||||
|
// Mendapatkan alamat lengkap dokumen
|
||||||
|
echo "Alamat dokumen ini adalah " . __FILE__;
|
||||||
|
|
||||||
|
// Mendapatkan nama fungsi
|
||||||
|
echo "Nama fungsi ini adalah " . __FUNCTION__;
|
||||||
|
|
||||||
|
// Mendapatkan nomor baris perintah
|
||||||
|
echo "Nomor baris perintah ini adalah " . __LINE__;
|
||||||
|
|
||||||
|
// Mendapatkan nama method. Hanya mengembalikan sebuah nilai jika berada didalam trait atau deklarasi objek.
|
||||||
|
echo "Nama method ini adalah " . __METHOD__;
|
||||||
|
|
||||||
|
// Mendapatkan nama namespace
|
||||||
|
echo "Namespace saat ini adalah " . __NAMESPACE__;
|
||||||
|
|
||||||
|
// Mendapatkan nama dari trait. Hanya mengembalikan sebuah nilai jika berada didalam trait atau deklarasi objek.
|
||||||
|
echo "Namespace saat ini adalah " . __TRAIT__;
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* Penanganan Kesalahan (Error)
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Penanganan error sederhana menggunakan "try...catch"
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Kerjakan sesuatu
|
||||||
|
} catch (Exception $e) {
|
||||||
|
// Penanganan exception
|
||||||
|
}
|
||||||
|
|
||||||
|
// Menggunakan "try...catch" blok pada namespace
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Kerjakan sesuatu
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
// Penanganan exception
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exception khusus
|
||||||
|
|
||||||
|
class ExceptionSaya extends Exception {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
$kondisi = true;
|
||||||
|
|
||||||
|
if ($kondisi) {
|
||||||
|
throw new ExceptionSaya('Terjadi sesuatu');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (ExceptionSaya $e) {
|
||||||
|
// Penanganan untuk exception khusus
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Informasi lainnya
|
||||||
|
|
||||||
|
Kunjungi [Dokumentasi resmi PHP](http://www.php.net/manual/) untuk referensi dan masukan komunitas.
|
||||||
|
|
||||||
|
Jika anda tertarik untuk belajar lebih dalam, kunjungi
|
||||||
|
[PHP The Right Way](http://www.phptherightway.com/).
|
||||||
|
|
||||||
|
Jika anda terbiasa dengan manajemen paket, kunjungi
|
||||||
|
[Composer](http://getcomposer.org/).
|
||||||
|
|
||||||
|
Untuk standar umum, kunjungi PHP Framework Interoperability Group's
|
||||||
|
[PSR standards](https://github.com/php-fig/fig-standards).
|
@ -5,19 +5,76 @@ contributors:
|
|||||||
- ["João Farias", "https://github.com/JoaoGFarias"]
|
- ["João Farias", "https://github.com/JoaoGFarias"]
|
||||||
translators:
|
translators:
|
||||||
- ["Rizky Luthfianto", "https://github.com/rilut"]
|
- ["Rizky Luthfianto", "https://github.com/rilut"]
|
||||||
|
- ["Ahmad Zafrullah", "https://github.com/23Pstars"]
|
||||||
lang: id-id
|
lang: id-id
|
||||||
---
|
---
|
||||||
|
|
||||||
XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data.
|
XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. XML mudah dibaca oleh manusia dan mesin.
|
||||||
|
|
||||||
Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya.
|
Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya.
|
||||||
|
|
||||||
* Sintaks XML
|
Terdapat perbedaan antara **konten** dan **markup**. Singkatnya, konten dapat berupa apapun dan markup adalah sebagai penentu.
|
||||||
|
|
||||||
|
## Definisi dan Pendahuluan
|
||||||
|
|
||||||
|
Dokumen XML pada dasarnya disusun oleh *elemen* yang dapat memiliki *atribut* untuk menjelaskan elemen tersebut dan dapat memiliki beberapa konten tekstual atau beberapa elemen sebagai anak-nya. Setiap dokumen XML hendaknya memiliki satu elemen akar, yang menjadi induk dari semua elemen dalam dokumen XML.
|
||||||
|
|
||||||
|
Pengurai XML dirancang menjadi sangat ketat, dan akan berhenti melakukan penguraian terhadap dokumen yang cacat. Oleh karena itu semua dokumen XML harus mengikuti [Aturan Sintaks XML](http://www.w3schools.com/xml/xml_syntax.asp).
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<!-- Komentar di XML seperti ini -->
|
<!-- Ini adalah komentar. Komentar harus memiliki dua tanda penghubung secara berurutan (-). -->
|
||||||
|
<!-- Komentar dapat renggang
|
||||||
|
menjadi banyak baris -->
|
||||||
|
|
||||||
|
<!-- Elemen -->
|
||||||
|
<!-- Elemen merupakan komponen dasar dari XML. Ada dua tipe dari elemen, kosong: -->
|
||||||
|
<elemen1 atribut="nilai" /> <!-- Elemen kosong tidak memiliki konten apapun -->
|
||||||
|
<!-- dan tidak-kosong: -->
|
||||||
|
<elemen2 atribut="nilai">Konten</elemen2>
|
||||||
|
<!-- Nama elemen hanya dapat berupa huruf dan angka saja. -->
|
||||||
|
|
||||||
|
<kosong /> <!-- Elemen yang terdiri dari tag elemen kosong… -->
|
||||||
|
<!-- …tidak memiliki content apapun dan murni markup. -->
|
||||||
|
|
||||||
|
<tidakkosong> <!-- Atau, elemen ini memiliki tag pembuka… -->
|
||||||
|
<!-- …suatu konten… -->
|
||||||
|
</tidakkosong> <!-- dan sebuah tag penutup. -->
|
||||||
|
|
||||||
|
<!-- Nama elemen merupakan *case sensitive*. -->
|
||||||
|
<elemen />
|
||||||
|
<!-- …tidak sama dengan elemen sebelumnya -->
|
||||||
|
<eLEMEN />
|
||||||
|
|
||||||
|
<!-- Atribut -->
|
||||||
|
<!-- Sebuah atribut merupakan hubungan kunci-nilai yang terdapat pada elemen. -->
|
||||||
|
<elemen atribut="nilai" lainnya="nilaiLainnya" banyakNilai="daftar nilai ber-spasi" />
|
||||||
|
<!-- Sebuah atribut digunakan hanya sekali dalam sebuah elemen. Dan hanya memiliki satu nilai.
|
||||||
|
Salah satu solusi untuk mengatasi permasalahan tersebut adalah dengan menggunakan daftar nilai ber-spasi. -->
|
||||||
|
|
||||||
|
<!-- Elemen bersarang -->
|
||||||
|
<!-- Konten dari sebuah elemen dapat berupa elemen lainnya:: -->
|
||||||
|
<ayah>
|
||||||
|
<anak>Teks</anak>
|
||||||
|
<oranglain />
|
||||||
|
</ayah>
|
||||||
|
<!-- Mengikuti standar tatanan pohon. Setiap elemen disebut *node*.
|
||||||
|
Induk yang berada satu tingkat diatasnya disebut *parent*, keturunan yang berada satu tingkat dibawahnya disebut *children*.
|
||||||
|
Elemen yang berada pada *parent* yang sama disebut Saudara (*siblings*). -->
|
||||||
|
|
||||||
|
<!-- XML mempertahankan spasi. -->
|
||||||
|
<anak>
|
||||||
|
Teks
|
||||||
|
</anak>
|
||||||
|
<!-- …tidak sama dengan -->
|
||||||
|
<anak>Teks</anak>
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Dokumen XML
|
||||||
|
|
||||||
|
```xml
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!-- XML prolog, boleh tidak digunakan namun direkomendasikan untuk digunakan. -->
|
||||||
<tokobuku>
|
<tokobuku>
|
||||||
<buku category="MEMASAK">
|
<buku category="MEMASAK">
|
||||||
<judul lang="en">Everyday Italian</judul>
|
<judul lang="en">Everyday Italian</judul>
|
||||||
@ -65,7 +122,7 @@ Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data,
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
* Dokumen yang well-formated & Validasi
|
## Dokumen yang well-formated & Validasi
|
||||||
|
|
||||||
Sebuah dokumen XML disebut well-formated jika sintaksisnya benar.
|
Sebuah dokumen XML disebut well-formated jika sintaksisnya benar.
|
||||||
Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen,
|
Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen,
|
||||||
@ -128,3 +185,17 @@ Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi.
|
|||||||
</buku>
|
</buku>
|
||||||
</tokobuku>
|
</tokobuku>
|
||||||
```
|
```
|
||||||
|
## Kompatibilitas DTD dan Definisi Skema XML
|
||||||
|
|
||||||
|
Dukungan untuk DTD dapat ditemukan dimana-mana karena sudah sangat lama. Namun sayangnya, fitur XML terkini seperti *namespaces* tidak didukung oleh DTD. XML Xchema Definitions (XSDs) bertujuan untuk mengganti DTD dalam mendefinisikan tatabahasa dokumen XML.
|
||||||
|
|
||||||
|
## Sumber
|
||||||
|
|
||||||
|
* [Validasi dokumen XML](http://www.xmlvalidation.com)
|
||||||
|
|
||||||
|
## Bacaan lainnya
|
||||||
|
|
||||||
|
* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/)
|
||||||
|
* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp)
|
||||||
|
* [XML Tutorial](http://www.w3schools.com/xml/default.asp)
|
||||||
|
* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp)
|
||||||
|
195
inform7.html.markdown
Normal file
195
inform7.html.markdown
Normal file
@ -0,0 +1,195 @@
|
|||||||
|
---
|
||||||
|
language: Inform7
|
||||||
|
contributors:
|
||||||
|
- ["Hyphz", "http://github.com/hyphz/"]
|
||||||
|
filename: LearnInform.Inform
|
||||||
|
---
|
||||||
|
Inform 7 is a natural language based language created by Graham Nelson and Emily Short for writing text adventures, but also potentially usable for other text based applications, especially data backed ones.
|
||||||
|
|
||||||
|
```
|
||||||
|
"LearnInform" by Hyphz
|
||||||
|
|
||||||
|
[This is a comment.]
|
||||||
|
|
||||||
|
[Inform 7 is a language designed for building text adventures.
|
||||||
|
It can be used for other purposes too, although the default
|
||||||
|
library builds a text adventure. Inform 7 is object oriented.]
|
||||||
|
|
||||||
|
[This creates a class by subclassing. "Value" is the universal subclass,
|
||||||
|
but "object" is the most basic that behaves like an OO object.]
|
||||||
|
A datablock is a kind of object.
|
||||||
|
|
||||||
|
[Classes can have properties.]
|
||||||
|
A datablock can be broken. [This creates a boolean property.]
|
||||||
|
A datablock is usually not broken. [This sets its default value.]
|
||||||
|
A datablock can be big or small. [This creates an enumerated property.]
|
||||||
|
A datablock is usually small. [This sets its default value.]
|
||||||
|
A datablock has a number called the sequence number. [This creates a typed property.]
|
||||||
|
A datablock has some text called the name. ["Some text" means a string.]
|
||||||
|
A datablock has a datablock called the chain. [Declared classes become types.]
|
||||||
|
|
||||||
|
[This creates a global named instance.]
|
||||||
|
Block1 is a datablock.
|
||||||
|
The sequence number of Block1 is 1.
|
||||||
|
The name of Block1 is "Block One."
|
||||||
|
|
||||||
|
[Functions and procedures are defined as "phrases".]
|
||||||
|
To do the thing everyone does with their first program:
|
||||||
|
say "Hello World.". [Full stop indicates the end, indent indicates the scope.]
|
||||||
|
|
||||||
|
To dump (the block - a datablock): [That's how we create a parameter.]
|
||||||
|
say the sequence number of the block;
|
||||||
|
say the name of the block;
|
||||||
|
if the block is broken, say "(Broken)".
|
||||||
|
|
||||||
|
To toggle (the block - a datablock):
|
||||||
|
if the block is broken: [Conditional.]
|
||||||
|
now the block is not broken; [Updating a property.]
|
||||||
|
else:
|
||||||
|
now the block is broken.
|
||||||
|
|
||||||
|
[Multiple parameters.]
|
||||||
|
To fix (the broken block - a datablock) using (the repair block - a datablock):
|
||||||
|
if the broken block is not broken, stop; [Comma for a non indented single command.]
|
||||||
|
if the repair block is broken, stop;
|
||||||
|
now the sequence number of the broken block is the sequence number of the repair block;
|
||||||
|
now the broken block is not broken.
|
||||||
|
|
||||||
|
[Because of its text adventure origins, Inform 7 doesn't generally allow objects
|
||||||
|
to be created dynamically, although there's a language extension that enables it.]
|
||||||
|
Block2 is a datablock.
|
||||||
|
Block2 is broken.
|
||||||
|
The sequence number of Block2 is 2.
|
||||||
|
The name of Block2 is "Block two."
|
||||||
|
|
||||||
|
To demonstrate calling a phrase with two parameters:
|
||||||
|
Let the second block be block2; [Local pointer variable.]
|
||||||
|
fix the second block using Block1;
|
||||||
|
say the sequence number of the second block. [1.]
|
||||||
|
|
||||||
|
[Lists.]
|
||||||
|
To show how to use list types:
|
||||||
|
let the list be a list of datablocks;
|
||||||
|
add Block1 to the list;
|
||||||
|
add Block2 to the list;
|
||||||
|
say the list; ["Block1 and Block2"]
|
||||||
|
[Membership.]
|
||||||
|
if Block1 is listed in the list:
|
||||||
|
say "Block1 is there.";
|
||||||
|
[Loop.]
|
||||||
|
repeat with the block running through the list:
|
||||||
|
dump the block; [1 Block One. 1 Block Two.]
|
||||||
|
[Remember block two's sequence number was changed above.]
|
||||||
|
let X be entry 2 of the list; [Counting starts at 1.]
|
||||||
|
dump X; ["1 Block two."]
|
||||||
|
remove X from the list;
|
||||||
|
say the list. [Block1]
|
||||||
|
|
||||||
|
[Here's how we define a function and do arithmetic.]
|
||||||
|
|
||||||
|
To decide which number is the sum of all numbers up to (X - a number) (this is summing up):
|
||||||
|
let the total so far be a number;
|
||||||
|
repeat with the current number running from 1 to X:
|
||||||
|
now the total so far is the total so far + the current number;
|
||||||
|
decide on the total so far. [This is the return statement.]
|
||||||
|
|
||||||
|
[ We have higher order functions too. ]
|
||||||
|
|
||||||
|
To demonstrate a higher order function:
|
||||||
|
say summing up applied to {1, 2, 3, 4}.
|
||||||
|
|
||||||
|
To decide which number is the result of applying (phrase - phrase A -> A) twice to (B - a value of kind A):
|
||||||
|
let b1 be phrase applied to B;
|
||||||
|
let b2 be phrase applied to b1;
|
||||||
|
decide on b2.
|
||||||
|
|
||||||
|
To demonstrate defining a higher order function:
|
||||||
|
let X be 5;
|
||||||
|
say the result of applying summing up twice to X.
|
||||||
|
|
||||||
|
[ Rulebooks allow a number of functions which apply to the same type under different conditions to be stacked. ]
|
||||||
|
|
||||||
|
Datablock validation rules is a datablock based rulebook.
|
||||||
|
|
||||||
|
A datablock validation rule for a broken datablock: rule fails.
|
||||||
|
A datablock validation rule for a datablock (called the block):
|
||||||
|
dump the block;
|
||||||
|
rule succeeds.
|
||||||
|
|
||||||
|
To demonstrate invoking a rulebook:
|
||||||
|
follow datablock validation rules for Block1;
|
||||||
|
follow datablock validation rules for Block2.
|
||||||
|
|
||||||
|
[ Objects can also have relations, which resemble those in a relational database. ]
|
||||||
|
A dog is a kind of thing.
|
||||||
|
Rover is a dog.
|
||||||
|
The kennel is a container. [This is a built in base class.]
|
||||||
|
Rover is in the kennel. [This creates an inbuilt relation called "containment".]
|
||||||
|
|
||||||
|
[We can create relations by declaring their type.]
|
||||||
|
|
||||||
|
Guide dog ownership relates one dog to one person. [One-to-one.]
|
||||||
|
Property ownership relates various things to one person. [Many-to-one.]
|
||||||
|
Friendship relates various people to various people. [Many-to-many.]
|
||||||
|
|
||||||
|
[To actually use them we must assign verbs or prepositions to them.]
|
||||||
|
|
||||||
|
The verb to own means the property ownership relation.
|
||||||
|
The verb to be the guide dog of means the guide dog ownership relation.
|
||||||
|
The verb to be guided by means the reversed guide dog ownership relation.
|
||||||
|
The verb to be friends with means the friendship relation.
|
||||||
|
|
||||||
|
Edward is a person. A person can be blind. Edward is blind.
|
||||||
|
Edward is guided by Rover.
|
||||||
|
Benny is a person. Edward is friends with Benny.
|
||||||
|
|
||||||
|
To demonstrate looking something up with a relation:
|
||||||
|
repeat with the dog running through things that are the guide dog of Edward:
|
||||||
|
say the dog;
|
||||||
|
repeat with the friend running through things that are friends with Edward:
|
||||||
|
say the friend.
|
||||||
|
|
||||||
|
[We can also define relations that exist procedurally.]
|
||||||
|
|
||||||
|
Helpfulness relates a person (called the helper) to a person (called the helpee) when the helpee is blind and the helper is not blind.
|
||||||
|
The verb to be helpful to means the helpfulness relation.
|
||||||
|
To demonstrate using a procedural relation:
|
||||||
|
repeat with the helper running through people that are helpful to Edward:
|
||||||
|
say the helper.
|
||||||
|
|
||||||
|
|
||||||
|
[ Interface to the text adventure harness to allow the above code to be run. ]
|
||||||
|
Tutorial room is a room.
|
||||||
|
"A rather strange room full of buttons. Push them to run the exercises, or turn on the robot to run them all."
|
||||||
|
A button is a kind of thing. A button is fixed in place.
|
||||||
|
|
||||||
|
The red button is a button in tutorial room.
|
||||||
|
Instead of pushing the red button, do the thing everyone does with their first program.
|
||||||
|
The green button is a button in tutorial room.
|
||||||
|
Instead of pushing the green button, demonstrate calling a phrase with two parameters.
|
||||||
|
The blue button is a button in tutorial room.
|
||||||
|
Instead of pushing the blue button, show how to use list types.
|
||||||
|
The cyan button is a button in tutorial room.
|
||||||
|
Instead of pushing the cyan button, say the sum of all numbers up to 5.
|
||||||
|
The purple button is a button in tutorial room.
|
||||||
|
Instead of pushing the purple button, demonstrate a higher order function.
|
||||||
|
The black button is a button in tutorial room.
|
||||||
|
Instead of pushing the black button, demonstrate defining a higher order function.
|
||||||
|
The white button is a button in tutorial room.
|
||||||
|
Instead of pushing the white button, demonstrate invoking a rulebook.
|
||||||
|
The puce button is a button in tutorial room.
|
||||||
|
Instead of pushing the puce button, demonstrate looking something up with a relation.
|
||||||
|
The orange button is a button in tutorial room.
|
||||||
|
Instead of pushing the orange button, demonstrate using a procedural relation.
|
||||||
|
|
||||||
|
The robot is an object in tutorial room.
|
||||||
|
Instead of switching on the robot:
|
||||||
|
say "The robot begins to frantically flail its arms about.";
|
||||||
|
repeat with button running through buttons in the tutorial room:
|
||||||
|
say "The robot randomly hits [the button].";
|
||||||
|
try pushing button.
|
||||||
|
```
|
||||||
|
|
||||||
|
##Ready For More?
|
||||||
|
|
||||||
|
* [Inform 7](http://www.inform7.com/)
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
647
it-it/python-it.html.markdown
Normal file
647
it-it/python-it.html.markdown
Normal file
@ -0,0 +1,647 @@
|
|||||||
|
---
|
||||||
|
language: python
|
||||||
|
contributors:
|
||||||
|
- ["Louie Dinh", "http://ldinh.ca"]
|
||||||
|
- ["Amin Bandali", "http://aminbandali.com"]
|
||||||
|
- ["Andre Polykanine", "https://github.com/Oire"]
|
||||||
|
filename: learnpython.py
|
||||||
|
translators:
|
||||||
|
- ["Ale46", "http://github.com/Ale46/"]
|
||||||
|
lang: it-it
|
||||||
|
---
|
||||||
|
Python è stato creato da Guido Van Rossum agli inizi degli anni 90. Oggi è uno dei più popolari
|
||||||
|
linguaggi esistenti. Mi sono innamorato di Python per la sua chiarezza sintattica. E' sostanzialmente
|
||||||
|
pseudocodice eseguibile.
|
||||||
|
|
||||||
|
Feedback sono altamente apprezzati! Potete contattarmi su [@louiedinh](http://twitter.com/louiedinh) oppure [at] [google's email service]
|
||||||
|
|
||||||
|
Nota: Questo articolo è valido solamente per Python 2.7, ma dovrebbe andar bene anche per
|
||||||
|
Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
|
||||||
|
|
||||||
|
```python
|
||||||
|
|
||||||
|
# I commenti su una sola linea iniziano con un cancelletto
|
||||||
|
|
||||||
|
""" Più stringhe possono essere scritte
|
||||||
|
usando tre ", e sono spesso usate
|
||||||
|
come commenti
|
||||||
|
"""
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 1. Tipi di dati primitivi ed Operatori
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Hai i numeri
|
||||||
|
3 # => 3
|
||||||
|
|
||||||
|
# La matematica è quello che vi aspettereste
|
||||||
|
1 + 1 # => 2
|
||||||
|
8 - 1 # => 7
|
||||||
|
10 * 2 # => 20
|
||||||
|
35 / 5 # => 7
|
||||||
|
|
||||||
|
# La divisione è un po' complicata. E' una divisione fra interi in cui viene
|
||||||
|
# restituito in automatico il risultato intero.
|
||||||
|
5 / 2 # => 2
|
||||||
|
|
||||||
|
# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats.
|
||||||
|
2.0 # Questo è un float
|
||||||
|
11.0 / 4.0 # => 2.75 ahhh...molto meglio
|
||||||
|
|
||||||
|
# Il risultato di una divisione fra interi troncati positivi e negativi
|
||||||
|
5 // 3 # => 1
|
||||||
|
5.0 // 3.0 # => 1.0 # funziona anche per i floats
|
||||||
|
-5 // 3 # => -2
|
||||||
|
-5.0 // 3.0 # => -2.0
|
||||||
|
|
||||||
|
# Operazione Modulo
|
||||||
|
7 % 3 # => 1
|
||||||
|
|
||||||
|
# Elevamento a potenza (x alla y-esima potenza)
|
||||||
|
2**4 # => 16
|
||||||
|
|
||||||
|
# Forzare le precedenze con le parentesi
|
||||||
|
(1 + 3) * 2 # => 8
|
||||||
|
|
||||||
|
# Operatori Booleani
|
||||||
|
# Nota "and" e "or" sono case-sensitive
|
||||||
|
True and False #=> False
|
||||||
|
False or True #=> True
|
||||||
|
|
||||||
|
# Note sull'uso di operatori Bool con interi
|
||||||
|
0 and 2 #=> 0
|
||||||
|
-5 or 0 #=> -5
|
||||||
|
0 == False #=> True
|
||||||
|
2 == True #=> False
|
||||||
|
1 == True #=> True
|
||||||
|
|
||||||
|
# nega con not
|
||||||
|
not True # => False
|
||||||
|
not False # => True
|
||||||
|
|
||||||
|
# Uguaglianza è ==
|
||||||
|
1 == 1 # => True
|
||||||
|
2 == 1 # => False
|
||||||
|
|
||||||
|
# Disuguaglianza è !=
|
||||||
|
1 != 1 # => False
|
||||||
|
2 != 1 # => True
|
||||||
|
|
||||||
|
# Altri confronti
|
||||||
|
1 < 10 # => True
|
||||||
|
1 > 10 # => False
|
||||||
|
2 <= 2 # => True
|
||||||
|
2 >= 2 # => True
|
||||||
|
|
||||||
|
# I confronti possono essere concatenati!
|
||||||
|
1 < 2 < 3 # => True
|
||||||
|
2 < 3 < 2 # => False
|
||||||
|
|
||||||
|
# Le stringhe sono create con " o '
|
||||||
|
"Questa è una stringa."
|
||||||
|
'Anche questa è una stringa.'
|
||||||
|
|
||||||
|
# Anche le stringhe possono essere sommate!
|
||||||
|
"Ciao " + "mondo!" # => Ciao mondo!"
|
||||||
|
# Le stringhe possono essere sommate anche senza '+'
|
||||||
|
"Ciao " "mondo!" # => Ciao mondo!"
|
||||||
|
|
||||||
|
# ... oppure moltiplicate
|
||||||
|
"Hello" * 3 # => "HelloHelloHello"
|
||||||
|
|
||||||
|
# Una stringa può essere considerata come una lista di caratteri
|
||||||
|
"Questa è una stringa"[0] # => 'Q'
|
||||||
|
|
||||||
|
# % può essere usato per formattare le stringhe, in questo modo:
|
||||||
|
"%s possono essere %s" % ("le stringhe", "interpolate")
|
||||||
|
|
||||||
|
# Un nuovo modo per fomattare le stringhe è il metodo format.
|
||||||
|
# Questo metodo è quello consigliato
|
||||||
|
"{0} possono essere {1}".format("le stringhe", "formattate")
|
||||||
|
# Puoi usare delle parole chiave se non vuoi contare
|
||||||
|
"{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna")
|
||||||
|
|
||||||
|
# None è un oggetto
|
||||||
|
None # => None
|
||||||
|
|
||||||
|
# Non usare il simbolo di uguaglianza "==" per comparare oggetti a None
|
||||||
|
# Usa "is" invece
|
||||||
|
"etc" is None # => False
|
||||||
|
None is None # => True
|
||||||
|
|
||||||
|
# L'operatore 'is' testa l'identità di un oggetto. Questo non è
|
||||||
|
# molto utile quando non hai a che fare con valori primitivi, ma lo è
|
||||||
|
# quando hai a che fare con oggetti.
|
||||||
|
|
||||||
|
# None, 0, e stringhe/liste vuote sono tutte considerate a False.
|
||||||
|
# Tutti gli altri valori sono True
|
||||||
|
bool(0) # => False
|
||||||
|
bool("") # => False
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 2. Variabili e Collections
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Python ha una funzione di stampa
|
||||||
|
print "Sono Python. Piacere di conoscerti!"
|
||||||
|
|
||||||
|
# Non c'è bisogno di dichiarare una variabile per assegnarle un valore
|
||||||
|
una_variabile = 5 # Convenzionalmente si usa caratteri_minuscoli_con_underscores
|
||||||
|
una_variabile # => 5
|
||||||
|
|
||||||
|
# Accedendo ad una variabile non precedentemente assegnata genera un'eccezione.
|
||||||
|
# Dai un'occhiata al Control Flow per imparare di più su come gestire le eccezioni.
|
||||||
|
un_altra_variabile # Genera un errore di nome
|
||||||
|
|
||||||
|
# if può essere usato come un'espressione
|
||||||
|
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
|
||||||
|
|
||||||
|
# Liste immagazzinano sequenze
|
||||||
|
li = []
|
||||||
|
# Puoi partire con una lista pre-riempita
|
||||||
|
altra_li = [4, 5, 6]
|
||||||
|
|
||||||
|
# Aggiungi cose alla fine di una lista con append
|
||||||
|
li.append(1) # li ora è [1]
|
||||||
|
li.append(2) # li ora è [1, 2]
|
||||||
|
li.append(4) # li ora è [1, 2, 4]
|
||||||
|
li.append(3) # li ora è [1, 2, 4, 3]
|
||||||
|
# Rimuovi dalla fine della lista con pop
|
||||||
|
li.pop() # => 3 e li ora è [1, 2, 4]
|
||||||
|
# Rimettiamolo a posto
|
||||||
|
li.append(3) # li ora è [1, 2, 4, 3] di nuovo.
|
||||||
|
|
||||||
|
# Accedi ad una lista come faresti con un array
|
||||||
|
li[0] # => 1
|
||||||
|
# Assegna nuovo valore agli indici che sono già stati inizializzati con =
|
||||||
|
li[0] = 42
|
||||||
|
li[0] # => 42
|
||||||
|
li[0] = 1 # Nota: è resettato al valore iniziale
|
||||||
|
# Guarda l'ultimo elemento
|
||||||
|
li[-1] # => 3
|
||||||
|
|
||||||
|
# Guardare al di fuori dei limiti è un IndexError
|
||||||
|
li[4] # Genera IndexError
|
||||||
|
|
||||||
|
# Puoi guardare gli intervalli con la sintassi slice (a fetta).
|
||||||
|
# (E' un intervallo chiuso/aperto per voi tipi matematici.)
|
||||||
|
li[1:3] # => [2, 4]
|
||||||
|
# Ometti l'inizio
|
||||||
|
li[2:] # => [4, 3]
|
||||||
|
# Ometti la fine
|
||||||
|
li[:3] # => [1, 2, 4]
|
||||||
|
# Seleziona ogni seconda voce
|
||||||
|
li[::2] # =>[1, 4]
|
||||||
|
# Copia al contrario della lista
|
||||||
|
li[::-1] # => [3, 4, 2, 1]
|
||||||
|
# Usa combinazioni per fare slices avanzate
|
||||||
|
# li[inizio:fine:passo]
|
||||||
|
|
||||||
|
# Rimuovi arbitrariamente elementi da una lista con "del"
|
||||||
|
del li[2] # li è ora [1, 2, 3]
|
||||||
|
# Puoi sommare le liste
|
||||||
|
li + altra_li # => [1, 2, 3, 4, 5, 6]
|
||||||
|
# Nota: i valori per li ed altra_li non sono modificati.
|
||||||
|
|
||||||
|
# Concatena liste con "extend()"
|
||||||
|
li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6]
|
||||||
|
|
||||||
|
# Controlla l'esistenza di un valore in una lista con "in"
|
||||||
|
1 in li # => True
|
||||||
|
|
||||||
|
# Esamina la lunghezza con "len()"
|
||||||
|
len(li) # => 6
|
||||||
|
|
||||||
|
|
||||||
|
# Tuple sono come le liste ma immutabili.
|
||||||
|
tup = (1, 2, 3)
|
||||||
|
tup[0] # => 1
|
||||||
|
tup[0] = 3 # Genera un TypeError
|
||||||
|
|
||||||
|
# Puoi fare tutte queste cose da lista anche sulle tuple
|
||||||
|
len(tup) # => 3
|
||||||
|
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
|
||||||
|
tup[:2] # => (1, 2)
|
||||||
|
2 in tup # => True
|
||||||
|
|
||||||
|
# Puoi scompattare le tuple (o liste) in variabili
|
||||||
|
a, b, c = (1, 2, 3) # a è ora 1, b è ora 2 and c è ora 3
|
||||||
|
# Le tuple sono create di default se non usi le parentesi
|
||||||
|
d, e, f = 4, 5, 6
|
||||||
|
# Guarda come è facile scambiare due valori
|
||||||
|
e, d = d, e # d è ora 5 ed e è ora 4
|
||||||
|
|
||||||
|
|
||||||
|
# Dizionari immagazzinano mappature
|
||||||
|
empty_dict = {}
|
||||||
|
# Questo è un dizionario pre-riempito
|
||||||
|
filled_dict = {"uno": 1, "due": 2, "tre": 3}
|
||||||
|
|
||||||
|
# Accedi ai valori con []
|
||||||
|
filled_dict["uno"] # => 1
|
||||||
|
|
||||||
|
# Ottieni tutte le chiavi come una lista con "keys()"
|
||||||
|
filled_dict.keys() # => ["tre", "due", "uno"]
|
||||||
|
# Nota - Nei dizionari l'ordine delle chiavi non è garantito.
|
||||||
|
# Il tuo risultato potrebbe non essere uguale a questo.
|
||||||
|
|
||||||
|
# Ottieni tutt i valori come una lista con "values()"
|
||||||
|
filled_dict.values() # => [3, 2, 1]
|
||||||
|
# Nota - Come sopra riguardo l'ordinamento delle chiavi.
|
||||||
|
|
||||||
|
# Controlla l'esistenza delle chiavi in un dizionario con "in"
|
||||||
|
"uno" in filled_dict # => True
|
||||||
|
1 in filled_dict # => False
|
||||||
|
|
||||||
|
# Cercando una chiave non esistente è un KeyError
|
||||||
|
filled_dict["quattro"] # KeyError
|
||||||
|
|
||||||
|
# Usa il metodo "get()" per evitare KeyError
|
||||||
|
filled_dict.get("uno") # => 1
|
||||||
|
filled_dict.get("quattro") # => None
|
||||||
|
# Il metodo get supporta un argomento di default quando il valore è mancante
|
||||||
|
filled_dict.get("uno", 4) # => 1
|
||||||
|
filled_dict.get("quattro", 4) # => 4
|
||||||
|
# nota che filled_dict.get("quattro") è ancora => None
|
||||||
|
# (get non imposta il valore nel dizionario)
|
||||||
|
|
||||||
|
# imposta il valore di una chiave con una sintassi simile alle liste
|
||||||
|
filled_dict["quattro"] = 4 # ora, filled_dict["quattro"] => 4
|
||||||
|
|
||||||
|
# "setdefault()" aggiunge al dizionario solo se la chiave data non è presente
|
||||||
|
filled_dict.setdefault("five", 5) # filled_dict["five"] è impostato a 5
|
||||||
|
filled_dict.setdefault("five", 6) # filled_dict["five"] è ancora 5
|
||||||
|
|
||||||
|
|
||||||
|
# Sets immagazzina ... sets (che sono come le liste, ma non possono contenere doppioni)
|
||||||
|
empty_set = set()
|
||||||
|
# Inizializza un "set()" con un po' di valori
|
||||||
|
some_set = set([1, 2, 2, 3, 4]) # some_set è ora set([1, 2, 3, 4])
|
||||||
|
|
||||||
|
# l'ordine non è garantito, anche se a volta può sembrare ordinato
|
||||||
|
another_set = set([4, 3, 2, 2, 1]) # another_set è ora set([1, 2, 3, 4])
|
||||||
|
|
||||||
|
# Da Python 2.7, {} può essere usato per dichiarare un set
|
||||||
|
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
|
||||||
|
|
||||||
|
# Aggiungere elementi ad un set
|
||||||
|
filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5}
|
||||||
|
|
||||||
|
# Fai intersezioni su un set con &
|
||||||
|
other_set = {3, 4, 5, 6}
|
||||||
|
filled_set & other_set # => {3, 4, 5}
|
||||||
|
|
||||||
|
# Fai unioni su set con |
|
||||||
|
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
|
||||||
|
|
||||||
|
# Fai differenze su set con -
|
||||||
|
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
|
||||||
|
|
||||||
|
# Controlla l'esistenza in un set con in
|
||||||
|
2 in filled_set # => True
|
||||||
|
10 in filled_set # => False
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 3. Control Flow
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Dichiariamo una variabile
|
||||||
|
some_var = 5
|
||||||
|
|
||||||
|
# Questo è un controllo if. L'indentazione è molto importante in python!
|
||||||
|
# stampa "some_var è più piccola di 10"
|
||||||
|
if some_var > 10:
|
||||||
|
print "some_var è decisamente più grande di 10."
|
||||||
|
elif some_var < 10: # Questa clausola elif è opzionale.
|
||||||
|
print "some_var è più piccola di 10."
|
||||||
|
else: # Anche questo è opzionale.
|
||||||
|
print "some_var è precisamente 10."
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
I cicli for iterano sulle liste
|
||||||
|
stampa:
|
||||||
|
cane è un mammifero
|
||||||
|
gatto è un mammifero
|
||||||
|
topo è un mammifero
|
||||||
|
"""
|
||||||
|
for animale in ["cane", "gatto", "topo"]:
|
||||||
|
# Puoi usare {0} per interpolare le stringhe formattate. (Vedi di seguito.)
|
||||||
|
print "{0} è un mammifero".format(animale)
|
||||||
|
|
||||||
|
"""
|
||||||
|
"range(numero)" restituisce una lista di numeri
|
||||||
|
da zero al numero dato
|
||||||
|
stampa:
|
||||||
|
0
|
||||||
|
1
|
||||||
|
2
|
||||||
|
3
|
||||||
|
"""
|
||||||
|
for i in range(4):
|
||||||
|
print i
|
||||||
|
|
||||||
|
"""
|
||||||
|
"range(lower, upper)" restituisce una lista di numeri
|
||||||
|
dal più piccolo (lower) al più grande (upper)
|
||||||
|
stampa:
|
||||||
|
4
|
||||||
|
5
|
||||||
|
6
|
||||||
|
7
|
||||||
|
"""
|
||||||
|
for i in range(4, 8):
|
||||||
|
print i
|
||||||
|
|
||||||
|
"""
|
||||||
|
I cicli while vengono eseguiti finchè una condizione viene a mancare
|
||||||
|
stampa:
|
||||||
|
0
|
||||||
|
1
|
||||||
|
2
|
||||||
|
3
|
||||||
|
"""
|
||||||
|
x = 0
|
||||||
|
while x < 4:
|
||||||
|
print x
|
||||||
|
x += 1 # Forma compatta per x = x + 1
|
||||||
|
|
||||||
|
# Gestisci le eccezioni con un blocco try/except
|
||||||
|
|
||||||
|
# Funziona da Python 2.6 in su:
|
||||||
|
try:
|
||||||
|
# Usa "raise" per generare un errore
|
||||||
|
raise IndexError("Questo è un errore di indice")
|
||||||
|
except IndexError as e:
|
||||||
|
pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero.
|
||||||
|
except (TypeError, NameError):
|
||||||
|
pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario.
|
||||||
|
else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except
|
||||||
|
print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni
|
||||||
|
finally: # Eseguito sempre
|
||||||
|
print "Possiamo liberare risorse qui"
|
||||||
|
|
||||||
|
# Invece di try/finally per liberare risorse puoi usare il metodo with
|
||||||
|
with open("myfile.txt") as f:
|
||||||
|
for line in f:
|
||||||
|
print line
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 4. Funzioni
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Usa "def" per creare nuove funzioni
|
||||||
|
def aggiungi(x, y):
|
||||||
|
print "x è {0} e y è {1}".format(x, y)
|
||||||
|
return x + y # Restituisce valori con il metodo return
|
||||||
|
|
||||||
|
# Chiamare funzioni con parametri
|
||||||
|
aggiungi(5, 6) # => stampa "x è 5 e y è 6" e restituisce 11
|
||||||
|
|
||||||
|
# Un altro modo per chiamare funzioni è con parole chiave come argomenti
|
||||||
|
aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni ordine.
|
||||||
|
|
||||||
|
|
||||||
|
# Puoi definire funzioni che accettano un numero variabile di argomenti posizionali
|
||||||
|
# che verranno interpretati come tuple se non usi il *
|
||||||
|
def varargs(*args):
|
||||||
|
return args
|
||||||
|
|
||||||
|
varargs(1, 2, 3) # => (1, 2, 3)
|
||||||
|
|
||||||
|
|
||||||
|
# Puoi definire funzioni che accettano un numero variabile di parole chiave
|
||||||
|
# come argomento, che saranno interpretati come un dizionario se non usi **
|
||||||
|
def keyword_args(**kwargs):
|
||||||
|
return kwargs
|
||||||
|
|
||||||
|
# Chiamiamola per vedere cosa succede
|
||||||
|
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
|
||||||
|
|
||||||
|
|
||||||
|
# Puoi farle entrambi in una volta, se ti va
|
||||||
|
def all_the_args(*args, **kwargs):
|
||||||
|
print args
|
||||||
|
print kwargs
|
||||||
|
"""
|
||||||
|
all_the_args(1, 2, a=3, b=4) stampa:
|
||||||
|
(1, 2)
|
||||||
|
{"a": 3, "b": 4}
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Quando chiami funzioni, puoi fare l'opposto di args/kwargs!
|
||||||
|
# Usa * per sviluppare gli argomenti posizionale ed usa ** per espandere gli argomenti parola chiave
|
||||||
|
args = (1, 2, 3, 4)
|
||||||
|
kwargs = {"a": 3, "b": 4}
|
||||||
|
all_the_args(*args) # equivalente a foo(1, 2, 3, 4)
|
||||||
|
all_the_args(**kwargs) # equivalente a foo(a=3, b=4)
|
||||||
|
all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4)
|
||||||
|
|
||||||
|
# puoi passare args e kwargs insieme alle altre funzioni che accettano args/kwargs
|
||||||
|
# sviluppandoli, rispettivamente, con * e **
|
||||||
|
def pass_all_the_args(*args, **kwargs):
|
||||||
|
all_the_args(*args, **kwargs)
|
||||||
|
print varargs(*args)
|
||||||
|
print keyword_args(**kwargs)
|
||||||
|
|
||||||
|
# Funzioni Scope
|
||||||
|
x = 5
|
||||||
|
|
||||||
|
def setX(num):
|
||||||
|
# La variabile locale x non è uguale alla variabile globale x
|
||||||
|
x = num # => 43
|
||||||
|
print x # => 43
|
||||||
|
|
||||||
|
def setGlobalX(num):
|
||||||
|
global x
|
||||||
|
print x # => 5
|
||||||
|
x = num # la variabile globable x è ora 6
|
||||||
|
print x # => 6
|
||||||
|
|
||||||
|
setX(43)
|
||||||
|
setGlobalX(6)
|
||||||
|
|
||||||
|
# Python ha funzioni di prima classe
|
||||||
|
def create_adder(x):
|
||||||
|
def adder(y):
|
||||||
|
return x + y
|
||||||
|
return adder
|
||||||
|
|
||||||
|
add_10 = create_adder(10)
|
||||||
|
add_10(3) # => 13
|
||||||
|
|
||||||
|
# Ci sono anche funzioni anonime
|
||||||
|
(lambda x: x > 2)(3) # => True
|
||||||
|
|
||||||
|
# Esse sono incluse in funzioni di alto livello
|
||||||
|
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
||||||
|
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||||
|
|
||||||
|
# Possiamo usare la comprensione delle liste per mappe e filtri
|
||||||
|
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
|
||||||
|
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 5. Classi
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Usiamo una sottoclasse da un oggetto per avere una classe.
|
||||||
|
class Human(object):
|
||||||
|
|
||||||
|
# Un attributo della classe. E' condiviso da tutte le istanze delle classe
|
||||||
|
species = "H. sapiens"
|
||||||
|
|
||||||
|
# Costruttore base, richiamato quando la classe viene inizializzata.
|
||||||
|
# Si noti che il doppio leading e gli underscore finali denotano oggetti
|
||||||
|
# o attributi che sono usati da python ma che vivono nello spazio dei nome controllato
|
||||||
|
# dall'utente. Non dovresti usare nomi di questo genere.
|
||||||
|
def __init__(self, name):
|
||||||
|
# Assegna l'argomento all'attributo name dell'istanza
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
# Un metodo dell'istanza. Tutti i metodi prendo "self" come primo argomento
|
||||||
|
def say(self, msg):
|
||||||
|
return "{0}: {1}".format(self.name, msg)
|
||||||
|
|
||||||
|
# Un metodo della classe è condiviso fra tutte le istanze
|
||||||
|
# Sono chiamate con la classe chiamante come primo argomento
|
||||||
|
@classmethod
|
||||||
|
def get_species(cls):
|
||||||
|
return cls.species
|
||||||
|
|
||||||
|
# Un metodo statico è chiamato senza una classe od una istanza di riferimento
|
||||||
|
@staticmethod
|
||||||
|
def grunt():
|
||||||
|
return "*grunt*"
|
||||||
|
|
||||||
|
|
||||||
|
# Instanziare una classe
|
||||||
|
i = Human(name="Ian")
|
||||||
|
print i.say("hi") # stampa "Ian: hi"
|
||||||
|
|
||||||
|
j = Human("Joel")
|
||||||
|
print j.say("hello") # stampa "Joel: hello"
|
||||||
|
|
||||||
|
# Chiamare metodi della classe
|
||||||
|
i.get_species() # => "H. sapiens"
|
||||||
|
|
||||||
|
# Cambiare l'attributo condiviso
|
||||||
|
Human.species = "H. neanderthalensis"
|
||||||
|
i.get_species() # => "H. neanderthalensis"
|
||||||
|
j.get_species() # => "H. neanderthalensis"
|
||||||
|
|
||||||
|
# Chiamare il metodo condiviso
|
||||||
|
Human.grunt() # => "*grunt*"
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 6. Moduli
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Puoi importare moduli
|
||||||
|
import math
|
||||||
|
print math.sqrt(16) # => 4
|
||||||
|
|
||||||
|
# Puoi ottenere specifiche funzione da un modulo
|
||||||
|
from math import ceil, floor
|
||||||
|
print ceil(3.7) # => 4.0
|
||||||
|
print floor(3.7) # => 3.0
|
||||||
|
|
||||||
|
# Puoi importare tutte le funzioni da un modulo
|
||||||
|
# Attenzione: questo non è raccomandato
|
||||||
|
from math import *
|
||||||
|
|
||||||
|
# Puoi abbreviare i nomi dei moduli
|
||||||
|
import math as m
|
||||||
|
math.sqrt(16) == m.sqrt(16) # => True
|
||||||
|
# puoi anche verificare che le funzioni sono equivalenti
|
||||||
|
from math import sqrt
|
||||||
|
math.sqrt == m.sqrt == sqrt # => True
|
||||||
|
|
||||||
|
# I moduli di Python sono normali file python. Ne puoi
|
||||||
|
# scrivere di tuoi ed importarli. Il nome del modulo
|
||||||
|
# è lo stesso del nome del file.
|
||||||
|
|
||||||
|
# Potete scoprire quali funzioni e attributi
|
||||||
|
# definiscono un modulo
|
||||||
|
import math
|
||||||
|
dir(math)
|
||||||
|
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 7. Avanzate
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# I generatori ti aiutano a fare codice pigro
|
||||||
|
def double_numbers(iterable):
|
||||||
|
for i in iterable:
|
||||||
|
yield i + i
|
||||||
|
|
||||||
|
# Un generatore crea valori al volo.
|
||||||
|
# Invece di generare e ritornare tutti i valori in una volta ne crea uno in ciascuna
|
||||||
|
# iterazione. Ciò significa che i valori più grandi di 15 non saranno considerati in
|
||||||
|
# double_numbers.
|
||||||
|
# Nota xrange è un generatore che fa la stessa cosa di range.
|
||||||
|
# Creare una lista 1-900000000 occuperebbe molto tempo e spazio.
|
||||||
|
# xrange crea un oggetto generatore xrange invece di creare l'intera lista
|
||||||
|
# come fa range.
|
||||||
|
# Usiamo un underscore finale nel nome delle variabile quando vogliamo usare un nome
|
||||||
|
# che normalmente colliderebbe con una parola chiave di python
|
||||||
|
xrange_ = xrange(1, 900000000)
|
||||||
|
|
||||||
|
# raddoppierà tutti i numeri fino a che result >=30 non sarà trovato
|
||||||
|
for i in double_numbers(xrange_):
|
||||||
|
print i
|
||||||
|
if i >= 30:
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
# Decoratori
|
||||||
|
# in questo esempio beg include say
|
||||||
|
# Beg chiamerà say. Se say_please è True allora cambierà il messaggio
|
||||||
|
# ritornato
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
|
||||||
|
def beg(target_function):
|
||||||
|
@wraps(target_function)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
msg, say_please = target_function(*args, **kwargs)
|
||||||
|
if say_please:
|
||||||
|
return "{} {}".format(msg, "Per favore! Sono povero :(")
|
||||||
|
return msg
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
@beg
|
||||||
|
def say(say_please=False):
|
||||||
|
msg = "Puoi comprarmi una birra?"
|
||||||
|
return msg, say_please
|
||||||
|
|
||||||
|
|
||||||
|
print say() # Puoi comprarmi una birra?
|
||||||
|
print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :(
|
||||||
|
```
|
||||||
|
|
||||||
|
## Pronto per qualcosa di più?
|
||||||
|
|
||||||
|
### Gratis Online
|
||||||
|
|
||||||
|
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
|
||||||
|
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
|
||||||
|
* [Dive Into Python](http://www.diveintopython.net/)
|
||||||
|
* [The Official Docs](http://docs.python.org/2.6/)
|
||||||
|
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
|
||||||
|
* [Python Module of the Week](http://pymotw.com/2/)
|
||||||
|
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
|
||||||
|
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
|
||||||
|
|
||||||
|
### Libri cartacei
|
||||||
|
|
||||||
|
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
|
||||||
|
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
|
||||||
|
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
|
777
ja-jp/php-jp.html.markdown
Normal file
777
ja-jp/php-jp.html.markdown
Normal file
@ -0,0 +1,777 @@
|
|||||||
|
---
|
||||||
|
language: PHP
|
||||||
|
contributors:
|
||||||
|
- ["Malcolm Fell", "http://emarref.net/"]
|
||||||
|
- ["Trismegiste", "https://github.com/Trismegiste"]
|
||||||
|
translators:
|
||||||
|
- ["Kazushige Tominaga", "https://github.com/kazu9su"]
|
||||||
|
filename: learnphp-jp.php
|
||||||
|
lang: ja-jp
|
||||||
|
---
|
||||||
|
|
||||||
|
このドキュメントでは、 PHP 5+ について説明します。
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php // PHPのコードは、<?php タグで囲む必要があります。
|
||||||
|
|
||||||
|
// もしあなたのphpファイルがPHPのみで構成される場合、
|
||||||
|
// 意図しない出力を防ぐために、phpの閉じタグは省略するのがベストプラクティスです。
|
||||||
|
// 一行のコメントを書く場合、2つのスラッシュで始めます。
|
||||||
|
# ハッシュ(ポンド記号として知られる)を使いたいでしょうが、//のほうが一般的です
|
||||||
|
/*
|
||||||
|
スラッシュとアスタリスク、アスタリスクとスラッシュで囲むと、
|
||||||
|
複数行のコメントを書けます。
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 出力をプリントしたい場合は、"echo" か "print" を使います。
|
||||||
|
print('Hello '); // これは "Hello " という改行なしの文字列をプリントします。
|
||||||
|
|
||||||
|
// カッコ()はprintとecho関数に置いては省略できます。
|
||||||
|
echo "World\n"; // これは改行ありの"World"という文字列をプリントします。
|
||||||
|
// (全ての命令文では、セミコロンを最後に付けることが必須です。)
|
||||||
|
|
||||||
|
// <?php タグの外側にあるものは、自動的にプリントされます。
|
||||||
|
?>
|
||||||
|
Hello World Again!
|
||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
/************************************
|
||||||
|
* 型と変数について
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 変数は"$"マークで始まります
|
||||||
|
// 有効な変数名にするには、文字またはアンダースコア(_)で始めて,
|
||||||
|
// その後はどんな数字でも、文字でも、アンダースコアで続けても構いません
|
||||||
|
|
||||||
|
//ブーリアン値は大文字、小文字問いません
|
||||||
|
$boolean = true; // or TRUE or True
|
||||||
|
$boolean = false; // or FALSE or False
|
||||||
|
|
||||||
|
// 数値
|
||||||
|
$int1 = 12; // => 12
|
||||||
|
$int2 = -12; // => -12
|
||||||
|
$int3 = 012; // => 10 (先頭の0は8進法を示す)
|
||||||
|
$int4 = 0x0F; // => 15 (先頭の0xは16進法を示す)
|
||||||
|
|
||||||
|
// floats(浮動小数) (別名double)
|
||||||
|
$float = 1.234;
|
||||||
|
$float = 1.2e3;
|
||||||
|
$float = 7E-10;
|
||||||
|
|
||||||
|
// 変数の削除
|
||||||
|
unset($int1);
|
||||||
|
|
||||||
|
// 計算式
|
||||||
|
$sum = 1 + 1; // 2
|
||||||
|
$difference = 2 - 1; // 1
|
||||||
|
$product = 2 * 2; // 4
|
||||||
|
$quotient = 2 / 1; // 2
|
||||||
|
|
||||||
|
// 式の省略
|
||||||
|
$number = 0;
|
||||||
|
$number += 1; // $numberに1加算Increment $number by 1
|
||||||
|
echo $number++; // 1 がプリントされる(式の評価の後に加算される)
|
||||||
|
echo ++$number; // 3 がプリントされる(式の評価の前に加算される)
|
||||||
|
$number /= $float; // 割り算した結果の商を$numberに割り当てる
|
||||||
|
|
||||||
|
// 文字列はシングルクォートで囲むのが望ましいです
|
||||||
|
$sgl_quotes = '$String'; // => '$String'
|
||||||
|
|
||||||
|
// 文字列中に、他の変数を埋め込みたい場合以外は、ダブルクォートを使用するのはやめましょう
|
||||||
|
$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
|
||||||
|
|
||||||
|
// Special characters are only escaped in double quotes
|
||||||
|
// 特殊文字はダブルクォートによってのみ、エスケープされます
|
||||||
|
$escaped = "This contains a \t tab character.";
|
||||||
|
$unescaped = 'This just contains a slash and a t: \t';
|
||||||
|
|
||||||
|
// 必要があれば、変数を波括弧で囲みます
|
||||||
|
$money = "I have $${number} in the bank.";
|
||||||
|
|
||||||
|
// PHP 5.3から、nowdocs形式が変数の挿入をしない複数行の文字列の定義に使用できます
|
||||||
|
$nowdoc = <<<'END'
|
||||||
|
Multi line
|
||||||
|
string
|
||||||
|
END;
|
||||||
|
|
||||||
|
// ヒアドキュメント形式なら、文字列中に変数の挿入を行えます。
|
||||||
|
$heredoc = <<<END
|
||||||
|
Multi line
|
||||||
|
$sgl_quotes
|
||||||
|
END;
|
||||||
|
|
||||||
|
// 文字列の連結は . で行います
|
||||||
|
echo 'This string ' . 'is concatenated';
|
||||||
|
|
||||||
|
// 別々のパラメータとしてechoに渡すこともできます
|
||||||
|
echo 'Multiple', 'Parameters', 'Valid';
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* 定数
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 定数は define() を使って定義します
|
||||||
|
// また、実行中は変更することができないので注意が必要です!
|
||||||
|
|
||||||
|
// 有効は定数は文字かアンダースコアで始めます
|
||||||
|
// それ移行のは、どんな数値でも文字列でもアンダースコアでも構いません
|
||||||
|
define("FOO", "something");
|
||||||
|
|
||||||
|
// 定義した名前をそのまま($はつけずに)使用することで、定数にアクセスできます
|
||||||
|
// access to a constant is possible by direct using the choosen name
|
||||||
|
echo 'This outputs '.FOO;
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* 配列
|
||||||
|
*/
|
||||||
|
|
||||||
|
// PHPの配列はすべて連想配列です
|
||||||
|
|
||||||
|
// 連想配列は、他の言語ではハッシュ(ハッシュマップ)として知られています
|
||||||
|
|
||||||
|
// すべてのバージョンのPHPで動作します
|
||||||
|
$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
|
||||||
|
|
||||||
|
// PHP 5.4 から、新しいシンタックスが導入されました
|
||||||
|
$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
|
||||||
|
|
||||||
|
echo $associative['One']; // 1とプリントされます
|
||||||
|
|
||||||
|
// キーを指定しないシンプルな配列にも、自動的に数値キーが振られます
|
||||||
|
$array = ['One', 'Two', 'Three'];
|
||||||
|
echo $array[0]; // => "One"
|
||||||
|
|
||||||
|
// 配列の最後に要素を追加する
|
||||||
|
$array[] = 'Four';
|
||||||
|
// または、次のようにも書けます
|
||||||
|
array_push($array, 'Five');
|
||||||
|
|
||||||
|
// 配列から要素を削除
|
||||||
|
unset($array[3]);
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* 出力
|
||||||
|
*/
|
||||||
|
|
||||||
|
echo('Hello World!');
|
||||||
|
// 標準出力にHello World! とプリントします
|
||||||
|
// 標準出力はブラウザーで実行していればWebページに出力されます
|
||||||
|
// Stdout is the web page if running in a browser.
|
||||||
|
|
||||||
|
print('Hello World!'); // echoの結果と同じです
|
||||||
|
|
||||||
|
// echo は言語自体の構成要素であり、括弧なしで呼び出せます
|
||||||
|
// echo is actually a language construct, so you can drop the parentheses.
|
||||||
|
echo 'Hello World!';
|
||||||
|
print 'Hello World!'; // printも同様です
|
||||||
|
|
||||||
|
$paragraph = 'paragraph';
|
||||||
|
|
||||||
|
echo 100; // スカラー数値を直接出力します
|
||||||
|
echo $paragraph; // 変数も使用できます
|
||||||
|
|
||||||
|
// PHPタグの短縮型が設定されているか、使用しているPHPのバージョンが
|
||||||
|
// 5.4.0 以上であれば、短縮echoシンタックスを使用できます
|
||||||
|
?>
|
||||||
|
<p><?= $paragraph ?></p>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$x = 1;
|
||||||
|
$y = 2;
|
||||||
|
$x = $y; // $xに$yの値を代入します
|
||||||
|
$z = &$y;
|
||||||
|
// $zは$yへの参照です。
|
||||||
|
// $zの値を変更すると$yの値も変更されるでしょう。逆も同様です。
|
||||||
|
// $xは$yの最初の値を変わらず保持しています
|
||||||
|
|
||||||
|
echo $x; // => 2
|
||||||
|
echo $z; // => 2
|
||||||
|
$y = 0;
|
||||||
|
echo $x; // => 2
|
||||||
|
echo $z; // => 0
|
||||||
|
|
||||||
|
// 変数の型と値を標準出力へダンプします
|
||||||
|
var_dump($z); // int(0) と出力されます
|
||||||
|
|
||||||
|
// 人間が読めるフォーマットで変数を標準出力にプリントします
|
||||||
|
print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three )
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* ロジック
|
||||||
|
*/
|
||||||
|
$a = 0;
|
||||||
|
$b = '0';
|
||||||
|
$c = '1';
|
||||||
|
$d = '1';
|
||||||
|
|
||||||
|
// assertは引数がfalseの場合、Exceptionを投げます
|
||||||
|
|
||||||
|
//これらの比較は型が違ったとしても、常に真です。
|
||||||
|
assert($a == $b); // equality
|
||||||
|
assert($c != $a); // inequality
|
||||||
|
assert($c <> $a); // alternative inequality
|
||||||
|
assert($a < $c);
|
||||||
|
assert($c > $b);
|
||||||
|
assert($a <= $b);
|
||||||
|
assert($c >= $d);
|
||||||
|
|
||||||
|
// 次の比較は値が等しく、かつ同じ型である場合のみ真です
|
||||||
|
assert($c === $d);
|
||||||
|
assert($a !== $d);
|
||||||
|
assert(1 === '1');
|
||||||
|
assert(1 !== '1');
|
||||||
|
|
||||||
|
// spaceship演算子はPHP7から使用可能です
|
||||||
|
$a = 100;
|
||||||
|
$b = 1000;
|
||||||
|
|
||||||
|
echo $a <=> $a; // 等しいので0になります
|
||||||
|
echo $a <=> $b; // $a < $b なので -1 です
|
||||||
|
echo $b <=> $a; // $b > $a なので 1 です
|
||||||
|
|
||||||
|
// 変数は使用するコンテキストによって、変換されます
|
||||||
|
|
||||||
|
$integer = 1;
|
||||||
|
echo $integer + $integer; // => 2
|
||||||
|
|
||||||
|
$string = '1';
|
||||||
|
echo $string + $string; // => 2 (文字列は強制的に数値として処理されます)
|
||||||
|
|
||||||
|
$string = 'one';
|
||||||
|
echo $string + $string; // => 0
|
||||||
|
// '+'演算子は文字列'one'を数値にキャストできないので、0と出力されます
|
||||||
|
|
||||||
|
// 型のキャスティングによって、変数を指定したもう一つの型として扱うことができます
|
||||||
|
// Type casting can be used to treat a variable as another type
|
||||||
|
|
||||||
|
$boolean = (boolean) 1; // => true
|
||||||
|
|
||||||
|
$zero = 0;
|
||||||
|
$boolean = (boolean) $zero; // => false
|
||||||
|
|
||||||
|
// 型をキャストするため専用の関数も存在します
|
||||||
|
$integer = 5;
|
||||||
|
$string = strval($integer);
|
||||||
|
|
||||||
|
$var = null; // Null値
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* 制御構造
|
||||||
|
*/
|
||||||
|
|
||||||
|
if (true) {
|
||||||
|
print 'I get printed';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false) {
|
||||||
|
print 'I don\'t';
|
||||||
|
} else {
|
||||||
|
print 'I get printed';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (false) {
|
||||||
|
print 'Does not get printed';
|
||||||
|
} elseif(true) {
|
||||||
|
print 'Does';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 三項演算子
|
||||||
|
print (false ? 'Does not get printed' : 'Does');
|
||||||
|
|
||||||
|
// PHP 5.3から、三項演算子の短縮形が使用できます
|
||||||
|
// $x ? $x : 'Does'と同義です
|
||||||
|
$x = false;
|
||||||
|
print($x ?: 'Does');
|
||||||
|
|
||||||
|
// null合体演算子はPHP 7から使用できます
|
||||||
|
$a = null;
|
||||||
|
$b = 'Does print';
|
||||||
|
echo $a ?? 'a is not set'; // prints 'a is not set'
|
||||||
|
echo $b ?? 'b is not set'; // prints 'Does print'
|
||||||
|
|
||||||
|
|
||||||
|
$x = 0;
|
||||||
|
if ($x === '0') {
|
||||||
|
print 'Does not print';
|
||||||
|
} elseif($x == '1') {
|
||||||
|
print 'Does not print';
|
||||||
|
} else {
|
||||||
|
print 'Does print';
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// :を用いる別の構文はテンプレートで有用です
|
||||||
|
?>
|
||||||
|
|
||||||
|
<?php if ($x): ?>
|
||||||
|
この部分はifが真のとき表示されます
|
||||||
|
<?php else: ?>
|
||||||
|
それ以外の場合は、この部分が表示されます
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// いくつかのロジックを保存するにはswitchを使用します
|
||||||
|
switch ($x) {
|
||||||
|
case '0':
|
||||||
|
print 'Switch does type coercion';
|
||||||
|
break; // breakを書く必要があります。
|
||||||
|
// でなければ、次の'two', 'three'のcase文を続けて実行することになります。
|
||||||
|
case 'two':
|
||||||
|
case 'three':
|
||||||
|
// 変数が'two'または'three'の場合、何かを実行します
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
//デフォルトで何かを実行します
|
||||||
|
}
|
||||||
|
|
||||||
|
// while, do, forの構文は、おそらく他の言語とも共通なものです
|
||||||
|
$i = 0;
|
||||||
|
while ($i < 5) {
|
||||||
|
echo $i++;
|
||||||
|
}; // Prints "01234"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$i = 0;
|
||||||
|
do {
|
||||||
|
echo $i++;
|
||||||
|
} while ($i < 5); // Prints "01234"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
for ($x = 0; $x < 10; $x++) {
|
||||||
|
echo $x;
|
||||||
|
} // Prints "0123456789"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$wheels = ['bicycle' => 2, 'car' => 4];
|
||||||
|
|
||||||
|
//Foreachループによって、 配列を反復処理できます
|
||||||
|
foreach ($wheels as $wheel_count) {
|
||||||
|
echo $wheel_count;
|
||||||
|
} // Prints "24"
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
// 値と同じ様に、keyも反復処理できます
|
||||||
|
foreach ($wheels as $vehicle => $wheel_count) {
|
||||||
|
echo "A $vehicle has $wheel_count wheels";
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "\n";
|
||||||
|
|
||||||
|
$i = 0;
|
||||||
|
while ($i < 5) {
|
||||||
|
if ($i === 3) {
|
||||||
|
break; // Exit out of the while loop
|
||||||
|
}
|
||||||
|
echo $i++;
|
||||||
|
} // Prints "012"
|
||||||
|
|
||||||
|
for ($i = 0; $i < 5; $i++) {
|
||||||
|
if ($i === 3) {
|
||||||
|
continue; // Skip this iteration of the loop
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
} // Prints "0124"
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* 関数
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 関数を"function"で定義します
|
||||||
|
function my_function () {
|
||||||
|
return 'Hello';
|
||||||
|
}
|
||||||
|
|
||||||
|
echo my_function(); // => "Hello"
|
||||||
|
|
||||||
|
// 有効な関数名は、文字またはアンダースコアで始めます。それ以降は
|
||||||
|
// どれだけ長い文字、数値、アンダースコアを続けても構いません
|
||||||
|
|
||||||
|
function add ($x, $y = 1) { // $yはオプショナルな値であり、デフォルトで 1 です
|
||||||
|
$result = $x + $y;
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
echo add(4); // => 5
|
||||||
|
echo add(4, 2); // => 6
|
||||||
|
|
||||||
|
// $result には、関数の外からアクセス出来ません
|
||||||
|
// print $result; // エラーになります
|
||||||
|
|
||||||
|
// PHP 5.3 から、無名関数が使えます
|
||||||
|
$inc = function ($x) {
|
||||||
|
return $x + 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
echo $inc(2); // => 3
|
||||||
|
|
||||||
|
function foo ($x, $y, $z) {
|
||||||
|
echo "$x - $y - $z";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 関数は、関数を返すことができます
|
||||||
|
function bar ($x, $y) {
|
||||||
|
// 関数外の変数を利用したいときは、'use'を使います
|
||||||
|
return function ($z) use ($x, $y) {
|
||||||
|
foo($x, $y, $z);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$bar = bar('A', 'B');
|
||||||
|
$bar('C'); // Prints "A - B - C"
|
||||||
|
|
||||||
|
// 文字列を使って、定義済みの関数を呼び出すことができます
|
||||||
|
$function_name = 'add';
|
||||||
|
echo $function_name(1, 2); // => 3
|
||||||
|
|
||||||
|
// プログラミング中に、動的に動かす関数を決める場合に便利です。
|
||||||
|
// もしくは、call_user_func(callable $callback [, $parameter [, ... ]]) を使っても同じことができます
|
||||||
|
|
||||||
|
|
||||||
|
// 特に指定しなくても、渡された引数を受け取ることもできます
|
||||||
|
function parameters() {
|
||||||
|
$numargs = func_num_args();
|
||||||
|
if ($numargs > 0) {
|
||||||
|
echo func_get_arg(0) . ' | ';
|
||||||
|
}
|
||||||
|
$args_array = func_get_args();
|
||||||
|
foreach ($args_array as $key => $arg) {
|
||||||
|
echo $key . ' - ' . $arg . ' | ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World |
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* ファイルの読み込み
|
||||||
|
*/
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// 読み込まれたファイル中のPHPは、同じくPHPのオープンタグで始める必要があります
|
||||||
|
|
||||||
|
include 'my-file.php';
|
||||||
|
// my-file.php中のコードは、現在のスコープの中で使用可能です
|
||||||
|
// もしファイルを読み込めなければ (例:file not found)、警告が発せられます
|
||||||
|
|
||||||
|
include_once 'my-file.php';
|
||||||
|
// my-file.phpのコードが既にどこかで読み込まれていれば、
|
||||||
|
// ファイルを読み込みません。これは、クラスの多重定義のエラーを防ぎます
|
||||||
|
|
||||||
|
require 'my-file.php';
|
||||||
|
require_once 'my-file.php';
|
||||||
|
// include()と同じように、require()はもしファイルを読み込むことができなければ、
|
||||||
|
// 致命的エラーの原因となります
|
||||||
|
|
||||||
|
// my-include.phpの内容
|
||||||
|
<?php
|
||||||
|
|
||||||
|
return 'Anything you like.';
|
||||||
|
// End file
|
||||||
|
|
||||||
|
// include()とrequire()は一つの値を返します
|
||||||
|
$value = include 'my-include.php';
|
||||||
|
|
||||||
|
// ファイルは与えられたファイルパスを基に読み込まれます。
|
||||||
|
// ファイルパスを指定しない場合は、include_path の設定を利用します。
|
||||||
|
// もしファイルがinclude_path中に見つからない場合は、
|
||||||
|
// 呼び出し元スクリプトのディレクトリと作業ディレクトリの中も探します。
|
||||||
|
// それでも見つからない場合、失敗します。
|
||||||
|
/* */
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* クラス
|
||||||
|
*/
|
||||||
|
|
||||||
|
// クラスはclassキーワードで定義します
|
||||||
|
|
||||||
|
class MyClass
|
||||||
|
{
|
||||||
|
const MY_CONST = 'value'; // クラス定数です
|
||||||
|
|
||||||
|
static $staticVar = 'static';
|
||||||
|
|
||||||
|
// スタティック変数とアクセス制限
|
||||||
|
public static $publicStaticVar = 'publicStatic';
|
||||||
|
// クラス内でのみアクセス可能
|
||||||
|
private static $privateStaticVar = 'privateStatic';
|
||||||
|
// そのクラスと子クラスで参照可能
|
||||||
|
protected static $protectedStaticVar = 'protectedStatic';
|
||||||
|
|
||||||
|
// プロパティはアクセス制限を宣言する必要があります
|
||||||
|
public $property = 'public';
|
||||||
|
public $instanceProp;
|
||||||
|
protected $prot = 'protected'; // そのクラスと子クラスで参照可能
|
||||||
|
private $priv = 'private'; // クラス内でのみアクセス可能
|
||||||
|
|
||||||
|
// __constructでコンストラクターを生成します
|
||||||
|
public function __construct($instanceProp) {
|
||||||
|
// $thisでインスタンス変数にアクセスします
|
||||||
|
$this->instanceProp = $instanceProp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// メソッドはクラス内で関数として定義されます
|
||||||
|
public function myMethod()
|
||||||
|
{
|
||||||
|
print 'MyClass';
|
||||||
|
}
|
||||||
|
|
||||||
|
// finalキーワードは関数の上書きを禁止します
|
||||||
|
final function youCannotOverrideMe()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* クラスプロパティまたはメソッドをstaticとして作成すれば、
|
||||||
|
* クラスをインスタンス化(newすること)しなくてもアクセスできます。
|
||||||
|
* プロパティをstaticとして定義すると、
|
||||||
|
* インスタンス化されたクラスオブジェクトを通してのアクセスはできなくなります。
|
||||||
|
*/
|
||||||
|
|
||||||
|
public static function myStaticMethod()
|
||||||
|
{
|
||||||
|
print 'I am static';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// クラス定数は、いつでも静的にアクセスできます。
|
||||||
|
echo MyClass::MY_CONST; // Outputs 'value';
|
||||||
|
|
||||||
|
echo MyClass::$staticVar; // Outputs 'static';
|
||||||
|
MyClass::myStaticMethod(); // Outputs 'I am static';
|
||||||
|
|
||||||
|
// クラスをインスタンス化するには、newを使います。
|
||||||
|
$my_class = new MyClass('An instance property');
|
||||||
|
// 括弧はもし引数を渡す必要がなければ省略可能です。
|
||||||
|
|
||||||
|
// ->を使ってクラスのメンバにアクセスします。
|
||||||
|
echo $my_class->property; // => "public"
|
||||||
|
echo $my_class->instanceProp; // => "An instance property"
|
||||||
|
$my_class->myMethod(); // => "MyClass"
|
||||||
|
|
||||||
|
|
||||||
|
// extendsを使用してクラスを継承します。
|
||||||
|
class MyOtherClass extends MyClass
|
||||||
|
{
|
||||||
|
function printProtectedProperty()
|
||||||
|
{
|
||||||
|
echo $this->prot;
|
||||||
|
}
|
||||||
|
|
||||||
|
// メソッドを上書きします。
|
||||||
|
function myMethod()
|
||||||
|
{
|
||||||
|
parent::myMethod();
|
||||||
|
print ' > MyOtherClass';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$my_other_class = new MyOtherClass('Instance prop');
|
||||||
|
$my_other_class->printProtectedProperty(); // => Prints "protected"
|
||||||
|
$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass"
|
||||||
|
|
||||||
|
final class YouCannotExtendMe
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// 「マジックメソッド」を使ってゲッターとセッターを生成できます。
|
||||||
|
class MyMapClass
|
||||||
|
{
|
||||||
|
private $property;
|
||||||
|
|
||||||
|
public function __get($key)
|
||||||
|
{
|
||||||
|
return $this->$key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __set($key, $value)
|
||||||
|
{
|
||||||
|
$this->$key = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$x = new MyMapClass();
|
||||||
|
echo $x->property; // __get() メソッドを使用します
|
||||||
|
$x->property = 'Something'; // __set() メソッドを使用します
|
||||||
|
|
||||||
|
// クラスは抽象クラスにもできます(abstractキーワードを使用します)し、
|
||||||
|
// インターフェースを実装することもできます(implementsキーワードを使用します)。
|
||||||
|
// インターフェースはinterfaceキーワードで定義します。
|
||||||
|
|
||||||
|
interface InterfaceOne
|
||||||
|
{
|
||||||
|
public function doSomething();
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InterfaceTwo
|
||||||
|
{
|
||||||
|
public function doSomethingElse();
|
||||||
|
}
|
||||||
|
|
||||||
|
// インターフェースは継承することができます
|
||||||
|
interface InterfaceThree extends InterfaceTwo
|
||||||
|
{
|
||||||
|
public function doAnotherContract();
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class MyAbstractClass implements InterfaceOne
|
||||||
|
{
|
||||||
|
public $x = 'doSomething';
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyConcreteClass extends MyAbstractClass implements InterfaceTwo
|
||||||
|
{
|
||||||
|
public function doSomething()
|
||||||
|
{
|
||||||
|
echo $x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function doSomethingElse()
|
||||||
|
{
|
||||||
|
echo 'doSomethingElse';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// クラスは1つ以上のインターフェースを実装できます。
|
||||||
|
class SomeOtherClass implements InterfaceOne, InterfaceTwo
|
||||||
|
{
|
||||||
|
public function doSomething()
|
||||||
|
{
|
||||||
|
echo 'doSomething';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function doSomethingElse()
|
||||||
|
{
|
||||||
|
echo 'doSomethingElse';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* トレイト
|
||||||
|
*/
|
||||||
|
|
||||||
|
// トレイトはPHP 5.4.0 以上で使用可能で、traitキーワードで定義します。
|
||||||
|
|
||||||
|
trait MyTrait
|
||||||
|
{
|
||||||
|
public function myTraitMethod()
|
||||||
|
{
|
||||||
|
print 'I have MyTrait';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyTraitfulClass
|
||||||
|
{
|
||||||
|
use MyTrait;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cls = new MyTraitfulClass();
|
||||||
|
$cls->myTraitMethod(); // Prints "I have MyTrait"
|
||||||
|
|
||||||
|
|
||||||
|
/********************************
|
||||||
|
* 名前空間
|
||||||
|
*/
|
||||||
|
|
||||||
|
// このセクションは名前空間の定義はファイルの先頭で宣言される必要があるため、
|
||||||
|
// 独立しています。
|
||||||
|
// そのケースには当てはまらないふりをして続けましょう。
|
||||||
|
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// デフォルトでは、クラスはグローバルな名前空間に存在し、
|
||||||
|
// バックスラッシュによって明確にコールできます。
|
||||||
|
|
||||||
|
$cls = new \MyClass();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// ファイルに名前空間をセットします
|
||||||
|
namespace My\Namespace;
|
||||||
|
|
||||||
|
class MyClass
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// (別のファイルからの呼び出し)
|
||||||
|
$cls = new My\Namespace\MyClass;
|
||||||
|
|
||||||
|
// 異なる名前空間からの呼び出し
|
||||||
|
namespace My\Other\Namespace;
|
||||||
|
|
||||||
|
use My\Namespace\MyClass;
|
||||||
|
|
||||||
|
$cls = new MyClass();
|
||||||
|
|
||||||
|
// 名前空間に別名をつけることもできます
|
||||||
|
|
||||||
|
namespace My\Other\Namespace;
|
||||||
|
|
||||||
|
use My\Namespace as SomeOtherNamespace;
|
||||||
|
|
||||||
|
$cls = new SomeOtherNamespace\MyClass();
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* エラーハンドリング
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
// シンプルなエラーハンドリングは、try catchを使えば行えます
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 処理を実行します
|
||||||
|
} catch ( Exception $e) {
|
||||||
|
// 例外を処理します
|
||||||
|
}
|
||||||
|
|
||||||
|
// try catchを名前空間を持った環境で使用するときは、次のようにします。
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Do something
|
||||||
|
// 処理を実行します
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
// 例外を処理します
|
||||||
|
}
|
||||||
|
|
||||||
|
// 例外のカスタマイズ
|
||||||
|
|
||||||
|
class MyException extends Exception {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
$condition = true;
|
||||||
|
|
||||||
|
if ($condition) {
|
||||||
|
throw new MyException('Something just happend');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (MyException $e) {
|
||||||
|
// Handle my exception
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## より詳しい情報
|
||||||
|
|
||||||
|
リファレンスを見るため、またコミュニティへの情報提供のために、 [PHP公式ドキュメント](http://www.php.net/manual/) を訪れてみてください。
|
||||||
|
|
||||||
|
もし最新のベストプラクティスに興味があるなら、
|
||||||
|
[PHP The Right Way](http://www.phptherightway.com/)を訪れてみてください。
|
||||||
|
|
||||||
|
|
||||||
|
もしあなたがよいパッケージマネジメント・システムを持つ言語で開発経験があるのなら、
|
||||||
|
[Composer](http://getcomposer.org/)も確かめてみてください。
|
||||||
|
|
||||||
|
|
||||||
|
共通基準を知るためには、PHP Framework Interoperability Groupの
|
||||||
|
[PSR standards](https://github.com/php-fig/fig-standards)にも訪れてみてください。
|
@ -128,7 +128,7 @@ public class LearnJava {
|
|||||||
//
|
//
|
||||||
// BigInteger can be initialized using an array of bytes or a string.
|
// BigInteger can be initialized using an array of bytes or a string.
|
||||||
|
|
||||||
BigInteger fooBigInteger = new BigDecimal(fooByteArray);
|
BigInteger fooBigInteger = new BigInteger(fooByteArray);
|
||||||
|
|
||||||
|
|
||||||
// BigDecimal - Immutable, arbitrary-precision signed decimal number
|
// BigDecimal - Immutable, arbitrary-precision signed decimal number
|
||||||
@ -144,7 +144,12 @@ public class LearnJava {
|
|||||||
// or by initializing the unscaled value (BigInteger) and scale (int).
|
// or by initializing the unscaled value (BigInteger) and scale (int).
|
||||||
|
|
||||||
BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
|
BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
|
||||||
|
|
||||||
|
// Be wary of the constructor that takes a float or double as
|
||||||
|
// the inaccuracy of the float/double will be copied in BigDecimal.
|
||||||
|
// Prefer the String constructor when you need an exact value.
|
||||||
|
|
||||||
|
BigDecimal tenCents = new BigDecimal("0.1");
|
||||||
|
|
||||||
|
|
||||||
// Strings
|
// Strings
|
||||||
@ -170,7 +175,7 @@ public class LearnJava {
|
|||||||
// Another way to declare & initialize an array
|
// Another way to declare & initialize an array
|
||||||
int[] y = {9000, 1000, 1337};
|
int[] y = {9000, 1000, 1337};
|
||||||
String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
|
String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
|
||||||
boolean bools[] = new boolean[] {true, false, false};
|
boolean bools[] = {true, false, false};
|
||||||
|
|
||||||
// Indexing an array - Accessing an element
|
// Indexing an array - Accessing an element
|
||||||
System.out.println("intArray @ 0: " + intArray[0]);
|
System.out.println("intArray @ 0: " + intArray[0]);
|
||||||
@ -186,9 +191,9 @@ public class LearnJava {
|
|||||||
// operations perform as could be expected for a
|
// operations perform as could be expected for a
|
||||||
// doubly-linked list.
|
// doubly-linked list.
|
||||||
// Maps - A set of objects that map keys to values. Map is
|
// Maps - A set of objects that map keys to values. Map is
|
||||||
// an interface and therefore cannot be instantiated.
|
// an interface and therefore cannot be instantiated.
|
||||||
// The type of keys and values contained in a Map must
|
// The type of keys and values contained in a Map must
|
||||||
// be specified upon instantiation of the implementing
|
// be specified upon instantiation of the implementing
|
||||||
// class. Each key may map to only one corresponding value,
|
// class. Each key may map to only one corresponding value,
|
||||||
// and each key may appear only once (no duplicates).
|
// and each key may appear only once (no duplicates).
|
||||||
// HashMaps - This class uses a hashtable to implement the Map
|
// HashMaps - This class uses a hashtable to implement the Map
|
||||||
@ -207,8 +212,8 @@ public class LearnJava {
|
|||||||
System.out.println("1+2 = " + (i1 + i2)); // => 3
|
System.out.println("1+2 = " + (i1 + i2)); // => 3
|
||||||
System.out.println("2-1 = " + (i2 - i1)); // => 1
|
System.out.println("2-1 = " + (i2 - i1)); // => 1
|
||||||
System.out.println("2*1 = " + (i2 * i1)); // => 2
|
System.out.println("2*1 = " + (i2 * i1)); // => 2
|
||||||
System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
|
System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int)
|
||||||
System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5
|
System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
|
||||||
|
|
||||||
// Modulo
|
// Modulo
|
||||||
System.out.println("11%3 = "+(11 % 3)); // => 2
|
System.out.println("11%3 = "+(11 % 3)); // => 2
|
||||||
@ -416,7 +421,7 @@ public class LearnJava {
|
|||||||
// easier way, by using something that is called Double Brace
|
// easier way, by using something that is called Double Brace
|
||||||
// Initialization.
|
// Initialization.
|
||||||
|
|
||||||
private static final Set<String> COUNTRIES = HashSet<String>() {{
|
private static final Set<String> COUNTRIES = new HashSet<String>() {{
|
||||||
add("DENMARK");
|
add("DENMARK");
|
||||||
add("SWEDEN");
|
add("SWEDEN");
|
||||||
add("FINLAND");
|
add("FINLAND");
|
||||||
@ -433,7 +438,7 @@ public class LearnJava {
|
|||||||
|
|
||||||
|
|
||||||
// You can include other, non-public outer-level classes in a .java file,
|
// You can include other, non-public outer-level classes in a .java file,
|
||||||
// but it is good practice. Instead split classes into separate files.
|
// but it is not good practice. Instead split classes into separate files.
|
||||||
|
|
||||||
|
|
||||||
// Class Declaration Syntax:
|
// Class Declaration Syntax:
|
||||||
@ -530,7 +535,7 @@ class PennyFarthing extends Bicycle {
|
|||||||
// (Penny Farthings are those bicycles with the big front wheel.
|
// (Penny Farthings are those bicycles with the big front wheel.
|
||||||
// They have no gears.)
|
// They have no gears.)
|
||||||
|
|
||||||
public PennyFarthing(int startCadence, int startSpeed){
|
public PennyFarthing(int startCadence, int startSpeed) {
|
||||||
// Call the parent constructor with super
|
// Call the parent constructor with super
|
||||||
super(startCadence, startSpeed, 0, "PennyFarthing");
|
super(startCadence, startSpeed, 0, "PennyFarthing");
|
||||||
}
|
}
|
||||||
@ -697,6 +702,66 @@ public abstract class Mammal()
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Enum Type
|
||||||
|
//
|
||||||
|
// An enum type is a special data type that enables for a variable to be a set
|
||||||
|
// of predefined constants. The variable must be equal to one of the values that
|
||||||
|
// have been predefined for it. Because they are constants, the names of an enum
|
||||||
|
// type's fields are in uppercase letters. In the Java programming language, you
|
||||||
|
// define an enum type by using the enum keyword. For example, you would specify
|
||||||
|
// a days-of-the-week enum type as:
|
||||||
|
|
||||||
|
public enum Day {
|
||||||
|
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
|
||||||
|
THURSDAY, FRIDAY, SATURDAY
|
||||||
|
}
|
||||||
|
|
||||||
|
// We can use our enum Day like that:
|
||||||
|
|
||||||
|
public class EnumTest {
|
||||||
|
|
||||||
|
// Variable Enum
|
||||||
|
Day day;
|
||||||
|
|
||||||
|
public EnumTest(Day day) {
|
||||||
|
this.day = day;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void tellItLikeItIs() {
|
||||||
|
switch (day) {
|
||||||
|
case MONDAY:
|
||||||
|
System.out.println("Mondays are bad.");
|
||||||
|
break;
|
||||||
|
|
||||||
|
case FRIDAY:
|
||||||
|
System.out.println("Fridays are better.");
|
||||||
|
break;
|
||||||
|
|
||||||
|
case SATURDAY:
|
||||||
|
case SUNDAY:
|
||||||
|
System.out.println("Weekends are best.");
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
System.out.println("Midweek days are so-so.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
EnumTest firstDay = new EnumTest(Day.MONDAY);
|
||||||
|
firstDay.tellItLikeItIs(); // => Mondays are bad.
|
||||||
|
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
|
||||||
|
thirdDay.tellItLikeItIs(); // => Midweek days are so-so.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enum types are much more powerful than we show above.
|
||||||
|
// The enum body can include methods and other fields.
|
||||||
|
// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
@ -720,7 +785,7 @@ The links provided here below are just to get an understanding of the topic, fee
|
|||||||
|
|
||||||
* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
|
* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
|
||||||
|
|
||||||
* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
|
* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
|
||||||
|
|
||||||
**Online Practice and Tutorials**
|
**Online Practice and Tutorials**
|
||||||
|
|
||||||
|
@ -16,13 +16,14 @@ JavaScript isn't just limited to web browsers, though: Node.js, a project that
|
|||||||
provides a standalone runtime for Google Chrome's V8 JavaScript engine, is
|
provides a standalone runtime for Google Chrome's V8 JavaScript engine, is
|
||||||
becoming more and more popular.
|
becoming more and more popular.
|
||||||
|
|
||||||
Feedback would be highly appreciated! You can reach me at
|
JavaScript has a C-like syntax, so if you've used languages like C or Java,
|
||||||
[@adambrenecki](https://twitter.com/adambrenecki), or
|
a lot of the basic syntax will already be familiar. Despite this, and despite
|
||||||
[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
|
the similarity in name, JavaScript's object model is significantly different to
|
||||||
|
Java's.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// Comments are like C's. Single-line comments start with two slashes,
|
// Single-line comments start with two slashes.
|
||||||
/* and multiline comments start with slash-star
|
/* Multiline comments start with slash-star,
|
||||||
and end with star-slash */
|
and end with star-slash */
|
||||||
|
|
||||||
// Statements can be terminated by ;
|
// Statements can be terminated by ;
|
||||||
@ -40,7 +41,7 @@ doStuff()
|
|||||||
|
|
||||||
// JavaScript has one number type (which is a 64-bit IEEE 754 double).
|
// JavaScript has one number type (which is a 64-bit IEEE 754 double).
|
||||||
// Doubles have a 52-bit mantissa, which is enough to store integers
|
// Doubles have a 52-bit mantissa, which is enough to store integers
|
||||||
// up to about 9✕10¹⁵ precisely.
|
// up to about 9✕10¹⁵ precisely.
|
||||||
3; // = 3
|
3; // = 3
|
||||||
1.5; // = 1.5
|
1.5; // = 1.5
|
||||||
|
|
||||||
@ -100,6 +101,10 @@ false;
|
|||||||
// Strings are concatenated with +
|
// Strings are concatenated with +
|
||||||
"Hello " + "world!"; // = "Hello world!"
|
"Hello " + "world!"; // = "Hello world!"
|
||||||
|
|
||||||
|
// ... which works with more than just strings
|
||||||
|
"1, 2, " + 3; // = "1, 2, 3"
|
||||||
|
"Hello " + ["world", "!"] // = "Hello world,!"
|
||||||
|
|
||||||
// and are compared with < and >
|
// and are compared with < and >
|
||||||
"a" < "b"; // = true
|
"a" < "b"; // = true
|
||||||
|
|
||||||
@ -140,7 +145,7 @@ undefined; // used to indicate a value is not currently present (although
|
|||||||
// character.
|
// character.
|
||||||
var someVar = 5;
|
var someVar = 5;
|
||||||
|
|
||||||
// if you leave the var keyword off, you won't get an error...
|
// If you leave the var keyword off, you won't get an error...
|
||||||
someOtherVar = 10;
|
someOtherVar = 10;
|
||||||
|
|
||||||
// ...but your variable will be created in the global scope, not in the scope
|
// ...but your variable will be created in the global scope, not in the scope
|
||||||
@ -149,7 +154,7 @@ someOtherVar = 10;
|
|||||||
// Variables declared without being assigned to are set to undefined.
|
// Variables declared without being assigned to are set to undefined.
|
||||||
var someThirdVar; // = undefined
|
var someThirdVar; // = undefined
|
||||||
|
|
||||||
// if you wan't to declare a couple of variables, then you could use a comma
|
// If you want to declare a couple of variables, then you could use a comma
|
||||||
// separator
|
// separator
|
||||||
var someFourthVar = 2, someFifthVar = 4;
|
var someFourthVar = 2, someFifthVar = 4;
|
||||||
|
|
||||||
@ -198,8 +203,6 @@ myObj.myFourthKey; // = undefined
|
|||||||
///////////////////////////////////
|
///////////////////////////////////
|
||||||
// 3. Logic and Control Structures
|
// 3. Logic and Control Structures
|
||||||
|
|
||||||
// The syntax for this section is almost identical to Java's.
|
|
||||||
|
|
||||||
// The `if` structure works as you'd expect.
|
// The `if` structure works as you'd expect.
|
||||||
var count = 1;
|
var count = 1;
|
||||||
if (count == 3){
|
if (count == 3){
|
||||||
@ -227,15 +230,15 @@ for (var i = 0; i < 5; i++){
|
|||||||
// will run 5 times
|
// will run 5 times
|
||||||
}
|
}
|
||||||
|
|
||||||
//The For/In statement loops iterates over every property across the entire prototype chain
|
// The for/in statement iterates over every property across the entire prototype chain.
|
||||||
var description = "";
|
var description = "";
|
||||||
var person = {fname:"Paul", lname:"Ken", age:18};
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
for (var x in person){
|
for (var x in person){
|
||||||
description += person[x] + " ";
|
description += person[x] + " ";
|
||||||
}
|
}
|
||||||
|
|
||||||
//If only want to consider properties attached to the object itself,
|
// To only consider properties attached to the object itself
|
||||||
//and not its prototypes use hasOwnProperty() check
|
// and not its prototypes, use the `hasOwnProperty()` check.
|
||||||
var description = "";
|
var description = "";
|
||||||
var person = {fname:"Paul", lname:"Ken", age:18};
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
for (var x in person){
|
for (var x in person){
|
||||||
@ -244,8 +247,9 @@ for (var x in person){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//for/in should not be used to iterate over an Array where the index order is important.
|
// For/in should not be used to iterate over an Array where the index order
|
||||||
//There is no guarantee that for/in will return the indexes in any particular order
|
// is important, as there is no guarantee that for/in will return the indexes
|
||||||
|
// in any particular order.
|
||||||
|
|
||||||
// && is logical and, || is logical or
|
// && is logical and, || is logical or
|
||||||
if (house.size == "big" && house.colour == "blue"){
|
if (house.size == "big" && house.colour == "blue"){
|
||||||
@ -260,7 +264,7 @@ var name = otherName || "default";
|
|||||||
|
|
||||||
|
|
||||||
// The `switch` statement checks for equality with `===`.
|
// The `switch` statement checks for equality with `===`.
|
||||||
// use 'break' after each case
|
// Use 'break' after each case
|
||||||
// or the cases after the correct one will be executed too.
|
// or the cases after the correct one will be executed too.
|
||||||
grade = 'B';
|
grade = 'B';
|
||||||
switch (grade) {
|
switch (grade) {
|
||||||
@ -507,6 +511,10 @@ myNumber === myNumberObj; // = false
|
|||||||
if (0){
|
if (0){
|
||||||
// This code won't execute, because 0 is falsy.
|
// This code won't execute, because 0 is falsy.
|
||||||
}
|
}
|
||||||
|
if (new Number(0)){
|
||||||
|
// This code will execute, because wrapped numbers are objects, and objects
|
||||||
|
// are always truthy.
|
||||||
|
}
|
||||||
|
|
||||||
// However, the wrapper objects and the regular builtins share a prototype, so
|
// However, the wrapper objects and the regular builtins share a prototype, so
|
||||||
// you can actually add functionality to a string, for instance.
|
// you can actually add functionality to a string, for instance.
|
||||||
@ -534,28 +542,42 @@ if (Object.create === undefined){ // don't overwrite it if it exists
|
|||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
|
||||||
The [Mozilla Developer
|
The [Mozilla Developer Network][1] provides excellent documentation for
|
||||||
Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides
|
JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you
|
||||||
excellent documentation for JavaScript as it's used in browsers. Plus, it's a
|
can help others out by sharing your own knowledge.
|
||||||
wiki, so as you learn more you can help others out by sharing your own
|
|
||||||
knowledge.
|
|
||||||
|
|
||||||
MDN's [A re-introduction to
|
MDN's [A re-introduction to JavaScript][2] covers much of the concepts covered
|
||||||
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
here in more detail. This guide has quite deliberately only covered the
|
||||||
covers much of the concepts covered here in more detail. This guide has quite
|
JavaScript language itself; if you want to learn more about how to use
|
||||||
deliberately only covered the JavaScript language itself; if you want to learn
|
JavaScript in web pages, start by learning about the [Document Object Model][3].
|
||||||
more about how to use JavaScript in web pages, start by learning about the
|
|
||||||
[Document Object
|
|
||||||
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
|
|
||||||
|
|
||||||
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
|
[Learn Javascript by Example and with Challenges][4] is a variant of this
|
||||||
|
reference with built-in challenges.
|
||||||
|
|
||||||
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
|
[JavaScript Garden][5] is an in-depth guide of all the counter-intuitive parts
|
||||||
guide of all the counter-intuitive parts of the language.
|
of the language.
|
||||||
|
|
||||||
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
|
[JavaScript: The Definitive Guide][6] is a classic guide and reference book.
|
||||||
|
|
||||||
In addition to direct contributors to this article, some content is adapted
|
[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal
|
||||||
from Louie Dinh's Python tutorial on this site, and the [JS
|
|
||||||
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples.
|
||||||
on the Mozilla Developer Network.
|
|
||||||
|
[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
|
||||||
|
|
||||||
|
|
||||||
|
In addition to direct contributors to this article, some content is adapted from
|
||||||
|
Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the
|
||||||
|
Mozilla Developer Network.
|
||||||
|
|
||||||
|
|
||||||
|
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
|
||||||
|
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
|
||||||
|
[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
|
||||||
|
[4]: http://www.learneroo.com/modules/64/nodes/350
|
||||||
|
[5]: http://bonsaiden.github.io/JavaScript-Garden/
|
||||||
|
[6]: http://www.amazon.com/gp/product/0596805527/
|
||||||
|
[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
|
||||||
|
[8]: http://eloquentjavascript.net/
|
||||||
|
[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
|
||||||
|
[10]: http://jstherightway.org/
|
||||||
|
@ -8,27 +8,24 @@ contributors:
|
|||||||
- ["Michael Neth", "https://github.com/infernocloud"]
|
- ["Michael Neth", "https://github.com/infernocloud"]
|
||||||
---
|
---
|
||||||
|
|
||||||
As JSON is an extremely simple data-interchange format, this is most likely going to be the simplest Learn X in Y Minutes ever.
|
JSON is an extremely simple data-interchange format. As [json.org](http://json.org) says, it is easy for humans to read and write and for machines to parse and generate.
|
||||||
|
|
||||||
|
A piece of JSON must represent either:
|
||||||
|
* A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
|
||||||
|
* An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence.
|
||||||
|
an array/list/sequence (`[ ]`) or a dictionary/object/associated array (`{ }`).
|
||||||
|
|
||||||
JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility.
|
JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility.
|
||||||
|
|
||||||
For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
For the purposes of this tutorial, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
||||||
|
|
||||||
A JSON value must be a number, a string, an array, an object, or one of the following 3 literal names: true, false, null.
|
Supported data types:
|
||||||
|
|
||||||
Supporting browsers are: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+.
|
* Strings: `"hello"`, `"\"A quote.\""`, `"\u0abe"`, `"Newline.\n"`
|
||||||
|
* Numbers: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
|
||||||
File extension for JSON files is ".json" and the MIME type for JSON text is "application/json".
|
* Objects: `{ "key": "value" }`
|
||||||
|
* Arrays: `["Values"]`
|
||||||
Many programming languages have support for serializing (encoding) and unserializing (decoding) JSON data into native data structures. Javascript has implicit support for manipulating JSON text as data.
|
* Miscellaneous: `true`, `false`, `null`
|
||||||
|
|
||||||
More information can be found at http://www.json.org/
|
|
||||||
|
|
||||||
JSON is built on two structures:
|
|
||||||
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
|
|
||||||
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
|
|
||||||
|
|
||||||
An object with various name/value pairs.
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@ -66,20 +63,20 @@ An object with various name/value pairs.
|
|||||||
|
|
||||||
"alternative style": {
|
"alternative style": {
|
||||||
"comment": "check this out!"
|
"comment": "check this out!"
|
||||||
, "comma position": "doesn't matter - as long as it's before the next key, then it's valid"
|
, "comma position": "doesn't matter, if it's before the next key, it's valid"
|
||||||
, "another comment": "how nice"
|
, "another comment": "how nice"
|
||||||
}
|
},
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
"whitespace": "Does not matter.",
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
"that was short": "And done. You now know everything JSON has to offer."
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
A single array of values by itself is also valid JSON.
|
## Further Reading
|
||||||
|
|
||||||
```json
|
* [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics.
|
||||||
[1, 2, 3, "text", true]
|
|
||||||
```
|
|
||||||
|
|
||||||
Objects can be a part of the array as well.
|
|
||||||
|
|
||||||
```json
|
|
||||||
[{"name": "Bob", "age": 25}, {"name": "Jane", "age": 29}, {"name": "Jack", "age": 31}]
|
|
||||||
```
|
|
||||||
|
@ -2,6 +2,7 @@
|
|||||||
language: Julia
|
language: Julia
|
||||||
contributors:
|
contributors:
|
||||||
- ["Leah Hanson", "http://leahhanson.us"]
|
- ["Leah Hanson", "http://leahhanson.us"]
|
||||||
|
- ["Pranit Bauva", "http://github.com/pranitbauva1997"]
|
||||||
filename: learnjulia.jl
|
filename: learnjulia.jl
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -102,6 +103,11 @@ false
|
|||||||
# Printing is easy
|
# Printing is easy
|
||||||
println("I'm Julia. Nice to meet you!")
|
println("I'm Julia. Nice to meet you!")
|
||||||
|
|
||||||
|
# String can be compared lexicographically
|
||||||
|
"good" > "bye" # => true
|
||||||
|
"good" == "good" # => true
|
||||||
|
"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true
|
||||||
|
|
||||||
####################################################
|
####################################################
|
||||||
## 2. Variables and Collections
|
## 2. Variables and Collections
|
||||||
####################################################
|
####################################################
|
||||||
@ -145,12 +151,16 @@ a = Int64[] # => 0-element Int64 Array
|
|||||||
|
|
||||||
# 1-dimensional array literals can be written with comma-separated values.
|
# 1-dimensional array literals can be written with comma-separated values.
|
||||||
b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6]
|
b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6]
|
||||||
|
b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6]
|
||||||
b[1] # => 4
|
b[1] # => 4
|
||||||
b[end] # => 6
|
b[end] # => 6
|
||||||
|
|
||||||
# 2-dimentional arrays use space-separated values and semicolon-separated rows.
|
# 2-dimentional arrays use space-separated values and semicolon-separated rows.
|
||||||
matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
|
matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
|
||||||
|
|
||||||
|
# Arrays of a particular Type
|
||||||
|
b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6]
|
||||||
|
|
||||||
# Add stuff to the end of a list with push! and append!
|
# Add stuff to the end of a list with push! and append!
|
||||||
push!(a,1) # => [1]
|
push!(a,1) # => [1]
|
||||||
push!(a,2) # => [1,2]
|
push!(a,2) # => [1,2]
|
||||||
@ -390,6 +400,14 @@ end
|
|||||||
|
|
||||||
add(5, 6) # => 11 after printing out "x is 5 and y is 6"
|
add(5, 6) # => 11 after printing out "x is 5 and y is 6"
|
||||||
|
|
||||||
|
# Compact assignment of functions
|
||||||
|
f_add(x, y) = x + y # => "f (generic function with 1 method)"
|
||||||
|
f_add(3, 4) # => 7
|
||||||
|
|
||||||
|
# Function can also return multiple values as tuple
|
||||||
|
f(x, y) = x + y, x - y
|
||||||
|
f(3, 4) # => (7, -1)
|
||||||
|
|
||||||
# You can define functions that take a variable number of
|
# You can define functions that take a variable number of
|
||||||
# positional arguments
|
# positional arguments
|
||||||
function varargs(args...)
|
function varargs(args...)
|
||||||
@ -723,7 +741,7 @@ code_native(square_area, (Float64,))
|
|||||||
# ret
|
# ret
|
||||||
#
|
#
|
||||||
# Note that julia will use floating point instructions if any of the
|
# Note that julia will use floating point instructions if any of the
|
||||||
# arguements are floats.
|
# arguments are floats.
|
||||||
# Let's calculate the area of a circle
|
# Let's calculate the area of a circle
|
||||||
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
|
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
|
||||||
circle_area(5) # 78.53981633974483
|
circle_area(5) # 78.53981633974483
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
@ -4,6 +4,7 @@ contributors:
|
|||||||
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
|
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
|
||||||
- ["Colton Kohnke", "http://github.com/voltnor"]
|
- ["Colton Kohnke", "http://github.com/voltnor"]
|
||||||
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
|
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
|
||||||
|
- ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
|
||||||
filename: learn-latex.tex
|
filename: learn-latex.tex
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -106,6 +107,9 @@ Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\
|
|||||||
% However, the math symbols only exist in math-mode.
|
% However, the math symbols only exist in math-mode.
|
||||||
% We can enter math-mode from text mode with the $ signs.
|
% We can enter math-mode from text mode with the $ signs.
|
||||||
% The opposite also holds true. Variable can also be rendered in math-mode.
|
% The opposite also holds true. Variable can also be rendered in math-mode.
|
||||||
|
% We can also enter math mode with \[\]
|
||||||
|
|
||||||
|
\[a^2 + b^2 = c^2 \]
|
||||||
|
|
||||||
My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
|
My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
|
||||||
I haven't found a Greek letter that yet that LaTeX doesn't know about!
|
I haven't found a Greek letter that yet that LaTeX doesn't know about!
|
||||||
@ -224,6 +228,15 @@ format you defined in Step 1.
|
|||||||
|
|
||||||
That's all for now!
|
That's all for now!
|
||||||
|
|
||||||
|
% Most often, you would want to have a references section in your document.
|
||||||
|
% The easiest way to set this up would be by using the bibliography section
|
||||||
|
\begin{thebibliography}{1}
|
||||||
|
% similar to other lists, the \bibitem command can be used to list items
|
||||||
|
% each entry can then be cited directly in the body of the text
|
||||||
|
\bibitem{latexwiki} The amazing LaTeX wikibook: {\em https://en.wikibooks.org/wiki/LaTeX}
|
||||||
|
\bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
|
||||||
|
\end{thebibliography}
|
||||||
|
|
||||||
% end the document
|
% end the document
|
||||||
\end{document}
|
\end{document}
|
||||||
```
|
```
|
||||||
|
379
less.html.markdown
Normal file
379
less.html.markdown
Normal file
@ -0,0 +1,379 @@
|
|||||||
|
---
|
||||||
|
language: less
|
||||||
|
filename: learnless.less
|
||||||
|
contributors:
|
||||||
|
- ["Saravanan Ganesh", "http://srrvnn.me"]
|
||||||
|
---
|
||||||
|
|
||||||
|
Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more.
|
||||||
|
Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code.
|
||||||
|
|
||||||
|
```css
|
||||||
|
|
||||||
|
|
||||||
|
//Single line comments are removed when Less is compiled to CSS.
|
||||||
|
|
||||||
|
/*Multi line comments are preserved. */
|
||||||
|
|
||||||
|
|
||||||
|
/*Variables
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* You can store a CSS value (such as a color) in a variable.
|
||||||
|
Use the '@' symbol to create a variable. */
|
||||||
|
|
||||||
|
@primary-color: #A3A4FF;
|
||||||
|
@secondary-color: #51527F;
|
||||||
|
@body-font: 'Roboto', sans-serif;
|
||||||
|
|
||||||
|
/* You can use the variables throughout your stylesheet.
|
||||||
|
Now if you want to change a color, you only have to make the change once.*/
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: @primary-color;
|
||||||
|
color: @secondary-color;
|
||||||
|
font-family: @body-font;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* This would compile to: */
|
||||||
|
body {
|
||||||
|
background-color: #A3A4FF;
|
||||||
|
color: #51527F;
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* This is much more maintainable than having to change the color
|
||||||
|
each time it appears throughout your stylesheet. */
|
||||||
|
|
||||||
|
|
||||||
|
/*Mixins
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* If you find you are writing the same code for more than one
|
||||||
|
element, you might want to reuse that easily.*/
|
||||||
|
|
||||||
|
.center {
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* You can use the mixin by simply adding the selector as a style */
|
||||||
|
|
||||||
|
div {
|
||||||
|
.center;
|
||||||
|
background-color: @primary-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*Which would compile to: */
|
||||||
|
.center {
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
}
|
||||||
|
div {
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background-color: #A3A4FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* You can omit the mixin code from being compiled by adding paranthesis
|
||||||
|
after the selector */
|
||||||
|
|
||||||
|
.center() {
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
div {
|
||||||
|
.center;
|
||||||
|
background-color: @primary-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*Which would compile to: */
|
||||||
|
div {
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background-color: #A3A4FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*Functions
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Less provides functions that can be used to accomplish a variety of
|
||||||
|
tasks. Consider the following */
|
||||||
|
|
||||||
|
/* Functions can be invoked by using their name and passing in the
|
||||||
|
required arguments */
|
||||||
|
body {
|
||||||
|
width: round(10.25px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer {
|
||||||
|
background-color: fadeout(#000000, 0.25)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compiles to: */
|
||||||
|
|
||||||
|
body {
|
||||||
|
width: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer {
|
||||||
|
background-color: rgba(0, 0, 0, 0.75);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* You may also define your own functions. Functions are very similar to
|
||||||
|
mixins. When trying to choose between a function or a mixin, remember
|
||||||
|
that mixins are best for generating CSS while functions are better for
|
||||||
|
logic that might be used throughout your Less code. The examples in
|
||||||
|
the Math Operators' section are ideal candidates for becoming a reusable
|
||||||
|
function. */
|
||||||
|
|
||||||
|
/* This function will take a target size and the parent size and calculate
|
||||||
|
and return the percentage */
|
||||||
|
|
||||||
|
.average(@x, @y) {
|
||||||
|
@average_result: ((@x + @y) / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
div {
|
||||||
|
.average(16px, 50px); // "call" the mixin
|
||||||
|
padding: @average_result; // use its "return" value
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compiles to: */
|
||||||
|
|
||||||
|
div {
|
||||||
|
padding: 33px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*Extend (Inheritance)
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Extend is a way to share the properties of one selector with another. */
|
||||||
|
|
||||||
|
.display {
|
||||||
|
height: 50px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.display-success {
|
||||||
|
&:extend(.display);
|
||||||
|
border-color: #22df56;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compiles to: */
|
||||||
|
.display,
|
||||||
|
.display-success {
|
||||||
|
height: 50px;
|
||||||
|
}
|
||||||
|
.display-success {
|
||||||
|
border-color: #22df56;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Extending a CSS statement is preferable to creating a mixin
|
||||||
|
because of the way it groups together the classes that all share
|
||||||
|
the same base styling. If this was done with a mixin, the properties
|
||||||
|
would be duplicated for each statement that
|
||||||
|
called the mixin. While it won't affect your workflow, it will
|
||||||
|
add unnecessary bloat to the files created by the Less compiler. */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Nesting
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Less allows you to nest selectors within selectors */
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style-type: none;
|
||||||
|
margin-top: 2em;
|
||||||
|
|
||||||
|
li {
|
||||||
|
background-color: #FF0000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* '&' will be replaced by the parent selector. */
|
||||||
|
/* You can also nest pseudo-classes. */
|
||||||
|
/* Keep in mind that over-nesting will make your code less maintainable.
|
||||||
|
Best practices recommend going no more than 3 levels deep when nesting.
|
||||||
|
For example: */
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style-type: none;
|
||||||
|
margin-top: 2em;
|
||||||
|
|
||||||
|
li {
|
||||||
|
background-color: red;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background-color: blue;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compiles to: */
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style-type: none;
|
||||||
|
margin-top: 2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul li {
|
||||||
|
background-color: red;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul li:hover {
|
||||||
|
background-color: blue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul li a {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*Partials and Imports
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Less allows you to create partial files. This can help keep your Less
|
||||||
|
code modularized. Partial files conventionally begin with an '_',
|
||||||
|
e.g. _reset.less. and are imported into a main less file that gets
|
||||||
|
compiled into CSS */
|
||||||
|
|
||||||
|
/* Consider the following CSS which we'll put in a file called _reset.less */
|
||||||
|
|
||||||
|
html,
|
||||||
|
body,
|
||||||
|
ul,
|
||||||
|
ol {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Less offers @import which can be used to import partials into a file.
|
||||||
|
This differs from the traditional CSS @import statement which makes
|
||||||
|
another HTTP request to fetch the imported file. Less takes the
|
||||||
|
imported file and combines it with the compiled code. */
|
||||||
|
|
||||||
|
@import 'reset';
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-size: 16px;
|
||||||
|
font-family: Helvetica, Arial, Sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compiles to: */
|
||||||
|
|
||||||
|
html, body, ul, ol {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-size: 16px;
|
||||||
|
font-family: Helvetica, Arial, Sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*Math Operations
|
||||||
|
==============================*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Less provides the following operators: +, -, *, /, and %. These can
|
||||||
|
be useful for calculating values directly in your Less files instead
|
||||||
|
of using values that you've already calculated by hand. Below is an example
|
||||||
|
of a setting up a simple two column design. */
|
||||||
|
|
||||||
|
@content-area: 960px;
|
||||||
|
@main-content: 600px;
|
||||||
|
@sidebar-content: 300px;
|
||||||
|
|
||||||
|
@main-size: @main-content / @content-area * 100%;
|
||||||
|
@sidebar-size: @sidebar-content / @content-area * 100%;
|
||||||
|
@gutter: 100% - (@main-size + @sidebar-size);
|
||||||
|
|
||||||
|
body {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
width: @main-size;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar {
|
||||||
|
width: @sidebar-size;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gutter {
|
||||||
|
width: @gutter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Compiles to: */
|
||||||
|
|
||||||
|
body {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
width: 62.5%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar {
|
||||||
|
width: 31.25%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gutter {
|
||||||
|
width: 6.25%;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Practice Less
|
||||||
|
|
||||||
|
If you want to play with Less in your browser, check out [LESS2CSS](http://lesscss.org/less-preview/).
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
Less can be used in any project as long as you have a program to compile it
|
||||||
|
into CSS. You'll want to verify that the CSS you're using is compatible
|
||||||
|
with your target browsers.
|
||||||
|
|
||||||
|
[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
|
||||||
|
|
||||||
|
## Further reading
|
||||||
|
* [Official Documentation](http://lesscss.org/features/)
|
81
lt-lt/json-lt.html.markdown
Normal file
81
lt-lt/json-lt.html.markdown
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
---
|
||||||
|
language: json
|
||||||
|
filename: learnjson.json
|
||||||
|
lang: lt-lt
|
||||||
|
contributors:
|
||||||
|
- ["Zygimantus", "https://github.com/zygimantus"]
|
||||||
|
---
|
||||||
|
|
||||||
|
JSON („džeisonas“) yra itin paprastas duomenų mainų formatas, todėl tai bus pati lengviausia „Learn X in Y Minutes“ pamoka.
|
||||||
|
|
||||||
|
JSON savo gryniausioje formoje neturi jokių komentarų, tačiau dauguma analizatorių priimtų C stiliaus komentarus (`//`, `/* */`). Kai kurie analizatoriai taip pat toleruoja gale esantį kablelį, pvz., kablelis po kiekvieno masyvo paskutinio elemento arba po paskutinio objekto lauko, tačiau jų reikėtų vengti dėl geresnio suderinamumo.
|
||||||
|
|
||||||
|
JSON reikšmė privalo būti skaičius, eilutė, masyvas, objektas arba viena reikšmė iš šių: true, false, null.
|
||||||
|
|
||||||
|
Palaikančios naršyklės yra: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+.
|
||||||
|
|
||||||
|
Failo plėtinys JSON failams yra „.json“, o MIME tipas yra „application/json“.
|
||||||
|
|
||||||
|
Dauguma programavimo kalbų palaiko JSON duomenų serializaciją (kodavimą) ir deserializaciją (dekodavimą) į natyviasias duomenų struktūras. Javascript turi visišką JSON teksto kaip duomenų manipuliavimo palaikymą.
|
||||||
|
|
||||||
|
Daugiau informacijos galima rasti http://www.json.org/
|
||||||
|
|
||||||
|
JSON yra pastatytas iš dviejų struktūrų:
|
||||||
|
* Vardų/reikšmių porų rinkinys. Daugomoje kalbų, tai yra realizuojama kaip objektas, įrašas, struktūra, žodynas, hash lentelė, sąrašas su raktais arba asociatyvusis masyvas.
|
||||||
|
* Rūšiuotas reikšmių sąrašas. Daugumoje kalbų, toks sąrašas yra realizuojama kaip masyvas, vektorius, sąrašas arba seka.
|
||||||
|
|
||||||
|
Objektas su įvairiomis vardo/reikšmės poromis.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"raktas": "reikšmė",
|
||||||
|
|
||||||
|
"raktai": "privalo visada būti uždaryti dvigubomis kabutėmis",
|
||||||
|
"skaičiai": 0,
|
||||||
|
"eilutės": "Labas, pasauli. Visas unikodas yra leidžiamas, kartu su \"vengimu\".",
|
||||||
|
"turi logiką?": true,
|
||||||
|
"niekas": null,
|
||||||
|
|
||||||
|
"didelis skaičius": 1.2e+100,
|
||||||
|
|
||||||
|
"objektai": {
|
||||||
|
"komentaras": "Dauguma tavo struktūrų ateis iš objektų.",
|
||||||
|
|
||||||
|
"masyvas": [0, 1, 2, 3, "Masyvas gali turėti bet ką savyje.", 5],
|
||||||
|
|
||||||
|
"kitas objektas": {
|
||||||
|
"komentaras": "Šie dalykai gali būti įdedami naudingai."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
"kvailumas": [
|
||||||
|
{
|
||||||
|
"kalio šaltiniai": ["bananai"]
|
||||||
|
},
|
||||||
|
[
|
||||||
|
[1, 0, 0, 0],
|
||||||
|
[0, 1, 0, 0],
|
||||||
|
[0, 0, 1, "neo"],
|
||||||
|
[0, 0, 0, 1]
|
||||||
|
]
|
||||||
|
],
|
||||||
|
|
||||||
|
"alternativus stilius": {
|
||||||
|
"komentaras": "tik pažiūrėk!"
|
||||||
|
, "kablelio padėti": "nesvarbi - kol jis prieš kitą raktą, tada teisingas"
|
||||||
|
, "kitas komentaras": "kaip gražu"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Paprastas reikšmių masyvas pats savaime yra galiojantis JSON.
|
||||||
|
|
||||||
|
```json
|
||||||
|
[1, 2, 3, "tekstas", true]
|
||||||
|
```
|
||||||
|
|
||||||
|
Objektai taip pat gali būti masyvų dalis.
|
||||||
|
|
||||||
|
```json
|
||||||
|
[{"vardas": "Jonas", "amžius": 25}, {"vardas": "Eglė", "amžius": 29}, {"vardas": "Petras", "amžius": 31}]
|
||||||
|
```
|
@ -190,7 +190,7 @@ end
|
|||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- A table can have a metatable that gives the table operator-overloadish
|
-- A table can have a metatable that gives the table operator-overloadish
|
||||||
-- behavior. Later we'll see how metatables support js-prototypey behavior.
|
-- behaviour. Later we'll see how metatables support js-prototypey behaviour.
|
||||||
|
|
||||||
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
|
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
|
||||||
f2 = {a = 2, b = 3}
|
f2 = {a = 2, b = 3}
|
||||||
|
@ -11,7 +11,7 @@ target to the most recent version of the source. Famously written over a
|
|||||||
weekend by Stuart Feldman in 1976, it is still widely used (particularly
|
weekend by Stuart Feldman in 1976, it is still widely used (particularly
|
||||||
on Unix) despite many competitors and criticisms.
|
on Unix) despite many competitors and criticisms.
|
||||||
|
|
||||||
There are many varieties of make in existance, this article assumes that
|
There are many varieties of make in existence, this article assumes that
|
||||||
we are using GNU make which is the standard on Linux.
|
we are using GNU make which is the standard on Linux.
|
||||||
|
|
||||||
```make
|
```make
|
||||||
@ -234,10 +234,8 @@ bar = 'hello'
|
|||||||
endif
|
endif
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### More Resources
|
### More Resources
|
||||||
|
|
||||||
+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
|
+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
|
||||||
+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
|
+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
|
||||||
+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
|
+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
|
||||||
|
|
||||||
|
@ -2,45 +2,65 @@
|
|||||||
language: markdown
|
language: markdown
|
||||||
contributors:
|
contributors:
|
||||||
- ["Dan Turkel", "http://danturkel.com/"]
|
- ["Dan Turkel", "http://danturkel.com/"]
|
||||||
|
- ["Jacob Ward", "http://github.com/JacobCWard/"]
|
||||||
filename: markdown.md
|
filename: markdown.md
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
|
Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
|
||||||
|
|
||||||
Give me as much feedback as you want! / Feel free to fork and pull request!
|
Markdown also varies in implementation from one parser to a next. This
|
||||||
|
guide will attempt to clarify when features are universal or when they are
|
||||||
|
specific to a certain parser.
|
||||||
|
|
||||||
|
- [HTML Elements](#html-elements)
|
||||||
|
- [Headings](#headings)
|
||||||
|
- [Simple Text Styles](#simple-text-styles)
|
||||||
|
- [Paragraphs](#paragraphs)
|
||||||
|
- [Lists](#lists)
|
||||||
|
- [Code blocks](#code-blocks)
|
||||||
|
- [Horizontal rule](#horizontal-rule)
|
||||||
|
- [Links](#links)
|
||||||
|
- [Images](#images)
|
||||||
|
- [Miscellany](#miscellany)
|
||||||
|
|
||||||
|
## HTML Elements
|
||||||
|
Markdown is a superset of HTML, so any HTML file is valid Markdown.
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that
|
<!--This means we can use HTML elements in Markdown, such as the comment element,
|
||||||
means we can use HTML elements in Markdown, such as the comment element, and
|
and they won't be affected by a markdown parser. However, if you create an HTML element
|
||||||
they won't be affected by a markdown parser. However, if you create an HTML
|
in your markdown file, you cannot use markdown syntax within that element's contents.-->
|
||||||
element in your markdown file, you cannot use markdown syntax within that
|
```
|
||||||
element's contents. -->
|
|
||||||
|
|
||||||
<!-- Markdown also varies in implementation from one parser to a next. This
|
## Headings
|
||||||
guide will attempt to clarify when features are universal or when they are
|
|
||||||
specific to a certain parser. -->
|
|
||||||
|
|
||||||
<!-- Headers -->
|
You can create HTML elements `<h1>` through `<h6>` easily by prepending the
|
||||||
<!-- You can create HTML elements <h1> through <h6> easily by prepending the
|
text you want to be in that element by a number of hashes (#).
|
||||||
text you want to be in that element by a number of hashes (#) -->
|
|
||||||
|
```markdown
|
||||||
# This is an <h1>
|
# This is an <h1>
|
||||||
## This is an <h2>
|
## This is an <h2>
|
||||||
### This is an <h3>
|
### This is an <h3>
|
||||||
#### This is an <h4>
|
#### This is an <h4>
|
||||||
##### This is an <h5>
|
##### This is an <h5>
|
||||||
###### This is an <h6>
|
###### This is an <h6>
|
||||||
|
```
|
||||||
|
Markdown also provides us with two alternative ways of indicating h1 and h2.
|
||||||
|
|
||||||
<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 -->
|
```markdown
|
||||||
This is an h1
|
This is an h1
|
||||||
=============
|
=============
|
||||||
|
|
||||||
This is an h2
|
This is an h2
|
||||||
-------------
|
-------------
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Simple text styles -->
|
## Simple text styles
|
||||||
<!-- Text can be easily styled as italic or bold using markdown -->
|
|
||||||
|
|
||||||
|
Text can be easily styled as italic or bold using markdown.
|
||||||
|
|
||||||
|
```markdown
|
||||||
*This text is in italics.*
|
*This text is in italics.*
|
||||||
_And so is this text._
|
_And so is this text._
|
||||||
|
|
||||||
@ -50,15 +70,20 @@ __And so is this text.__
|
|||||||
***This text is in both.***
|
***This text is in both.***
|
||||||
**_As is this!_**
|
**_As is this!_**
|
||||||
*__And this!__*
|
*__And this!__*
|
||||||
|
```
|
||||||
|
|
||||||
<!-- In Github Flavored Markdown, which is used to render markdown files on
|
In Github Flavored Markdown, which is used to render markdown files on
|
||||||
Github, we also have strikethrough: -->
|
Github, we also have strikethrough:
|
||||||
|
|
||||||
|
```markdown
|
||||||
~~This text is rendered with strikethrough.~~
|
~~This text is rendered with strikethrough.~~
|
||||||
|
```
|
||||||
|
## Paragraphs
|
||||||
|
|
||||||
<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or
|
Paragraphs are a one or multiple adjacent lines of text separated by one or
|
||||||
multiple blank lines. -->
|
multiple blank lines.
|
||||||
|
|
||||||
|
```markdown
|
||||||
This is a paragraph. I'm typing in a paragraph isn't this fun?
|
This is a paragraph. I'm typing in a paragraph isn't this fun?
|
||||||
|
|
||||||
Now I'm in paragraph 2.
|
Now I'm in paragraph 2.
|
||||||
@ -66,16 +91,20 @@ I'm still in paragraph 2 too!
|
|||||||
|
|
||||||
|
|
||||||
I'm in paragraph three!
|
I'm in paragraph three!
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
|
Should you ever want to insert an HTML <br /> tag, you can end a paragraph
|
||||||
with two or more spaces and then begin a new paragraph. -->
|
with two or more spaces and then begin a new paragraph.
|
||||||
|
|
||||||
|
```markdown
|
||||||
I end with two spaces (highlight me to see them).
|
I end with two spaces (highlight me to see them).
|
||||||
|
|
||||||
There's a <br /> above me!
|
There's a <br /> above me!
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Block quotes are easy and done with the > character. -->
|
Block quotes are easy and done with the > character.
|
||||||
|
|
||||||
|
```markdown
|
||||||
> This is a block quote. You can either
|
> This is a block quote. You can either
|
||||||
> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own.
|
> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own.
|
||||||
> It doesn't make a difference so long as they start with a `>`.
|
> It doesn't make a difference so long as they start with a `>`.
|
||||||
@ -84,9 +113,12 @@ There's a <br /> above me!
|
|||||||
>> of indentation?
|
>> of indentation?
|
||||||
> How neat is that?
|
> How neat is that?
|
||||||
|
|
||||||
<!-- Lists -->
|
```
|
||||||
<!-- Unordered lists can be made using asterisks, pluses, or hyphens -->
|
|
||||||
|
|
||||||
|
## Lists
|
||||||
|
Unordered lists can be made using asterisks, pluses, or hyphens.
|
||||||
|
|
||||||
|
```markdown
|
||||||
* Item
|
* Item
|
||||||
* Item
|
* Item
|
||||||
* Another item
|
* Another item
|
||||||
@ -102,159 +134,194 @@ or
|
|||||||
- Item
|
- Item
|
||||||
- Item
|
- Item
|
||||||
- One last item
|
- One last item
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Ordered lists are done with a number followed by a period -->
|
Ordered lists are done with a number followed by a period.
|
||||||
|
|
||||||
|
```markdown
|
||||||
1. Item one
|
1. Item one
|
||||||
2. Item two
|
2. Item two
|
||||||
3. Item three
|
3. Item three
|
||||||
|
```
|
||||||
|
|
||||||
<!-- You don't even have to label the items correctly and markdown will still
|
You don't even have to label the items correctly and markdown will still
|
||||||
render the numbers in order, but this may not be a good idea -->
|
render the numbers in order, but this may not be a good idea.
|
||||||
|
|
||||||
|
```markdown
|
||||||
1. Item one
|
1. Item one
|
||||||
1. Item two
|
1. Item two
|
||||||
1. Item three
|
1. Item three
|
||||||
<!-- (This renders the same as the above example) -->
|
```
|
||||||
|
(This renders the same as the above example)
|
||||||
|
|
||||||
<!-- You can also use sublists -->
|
You can also use sublists
|
||||||
|
|
||||||
|
```markdown
|
||||||
1. Item one
|
1. Item one
|
||||||
2. Item two
|
2. Item two
|
||||||
3. Item three
|
3. Item three
|
||||||
* Sub-item
|
* Sub-item
|
||||||
* Sub-item
|
* Sub-item
|
||||||
4. Item four
|
4. Item four
|
||||||
|
```
|
||||||
|
|
||||||
<!-- There are even task lists. This creates HTML checkboxes. -->
|
There are even task lists. This creates HTML checkboxes.
|
||||||
|
|
||||||
|
```markdown
|
||||||
Boxes below without the 'x' are unchecked HTML checkboxes.
|
Boxes below without the 'x' are unchecked HTML checkboxes.
|
||||||
- [ ] First task to complete.
|
- [ ] First task to complete.
|
||||||
- [ ] Second task that needs done
|
- [ ] Second task that needs done
|
||||||
This checkbox below will be a checked HTML checkbox.
|
This checkbox below will be a checked HTML checkbox.
|
||||||
- [x] This task has been completed
|
- [x] This task has been completed
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Code blocks -->
|
## Code blocks
|
||||||
<!-- You can indicate a code block (which uses the <code> element) by indenting
|
|
||||||
a line with four spaces or a tab -->
|
|
||||||
|
|
||||||
|
You can indicate a code block (which uses the `<code>` element) by indenting
|
||||||
|
a line with four spaces or a tab.
|
||||||
|
|
||||||
|
```markdown
|
||||||
This is code
|
This is code
|
||||||
So is this
|
So is this
|
||||||
|
```
|
||||||
|
|
||||||
<!-- You can also re-tab (or add an additional four spaces) for indentation
|
You can also re-tab (or add an additional four spaces) for indentation
|
||||||
inside your code -->
|
inside your code
|
||||||
|
|
||||||
|
```markdown
|
||||||
my_array.each do |item|
|
my_array.each do |item|
|
||||||
puts item
|
puts item
|
||||||
end
|
end
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Inline code can be created using the backtick character ` -->
|
Inline code can be created using the backtick character `
|
||||||
|
|
||||||
|
```markdown
|
||||||
John didn't even know what the `go_to()` function did!
|
John didn't even know what the `go_to()` function did!
|
||||||
|
```
|
||||||
|
|
||||||
<!-- In Github Flavored Markdown, you can use a special syntax for code -->
|
In Github Flavored Markdown, you can use a special syntax for code
|
||||||
|
|
||||||
\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
|
<pre>
|
||||||
|
<code class="highlight">```ruby
|
||||||
def foobar
|
def foobar
|
||||||
puts "Hello world!"
|
puts "Hello world!"
|
||||||
end
|
end
|
||||||
\`\`\` <!-- here too, no backslashes, just ``` -->
|
```</code></pre>
|
||||||
|
|
||||||
<!-- The above text doesn't require indenting, plus Github will use syntax
|
The above text doesn't require indenting, plus Github will use syntax
|
||||||
highlighting of the language you specify after the ``` -->
|
highlighting of the language you specify after the \`\`\`
|
||||||
|
|
||||||
<!-- Horizontal rule (<hr />) -->
|
## Horizontal rule
|
||||||
<!-- Horizontal rules are easily added with three or more asterisks or hyphens,
|
|
||||||
with or without spaces. -->
|
|
||||||
|
|
||||||
|
Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens,
|
||||||
|
with or without spaces.
|
||||||
|
|
||||||
|
```markdown
|
||||||
***
|
***
|
||||||
---
|
---
|
||||||
- - -
|
- - -
|
||||||
****************
|
****************
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Links -->
|
## Links
|
||||||
<!-- One of the best things about markdown is how easy it is to make links. Put
|
|
||||||
the text to display in hard brackets [] followed by the url in parentheses () -->
|
|
||||||
|
|
||||||
|
One of the best things about markdown is how easy it is to make links. Put
|
||||||
|
the text to display in hard brackets [] followed by the url in parentheses ()
|
||||||
|
|
||||||
|
```markdown
|
||||||
[Click me!](http://test.com/)
|
[Click me!](http://test.com/)
|
||||||
|
```
|
||||||
|
You can also add a link title using quotes inside the parentheses.
|
||||||
|
|
||||||
<!-- You can also add a link title using quotes inside the parentheses -->
|
```markdown
|
||||||
|
|
||||||
[Click me!](http://test.com/ "Link to Test.com")
|
[Click me!](http://test.com/ "Link to Test.com")
|
||||||
|
```
|
||||||
|
Relative paths work too.
|
||||||
|
|
||||||
<!-- Relative paths work too. -->
|
```markdown
|
||||||
|
|
||||||
[Go to music](/music/).
|
[Go to music](/music/).
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Markdown also supports reference style links -->
|
Markdown also supports reference style links.
|
||||||
|
|
||||||
[Click this link][link1] for more info about it!
|
<pre><code class="highlight">[<span class="nv">Click this link</span>][<span class="ss">link1</span>] for more info about it!
|
||||||
[Also check out this link][foobar] if you want to.
|
[<span class="nv">Also check out this link</span>][<span class="ss">foobar</span>] if you want to.
|
||||||
|
|
||||||
[link1]: http://test.com/ "Cool!"
|
[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
|
||||||
[foobar]: http://foobar.biz/ "Alright!"
|
[<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Alright!"</span></code></pre>
|
||||||
|
|
||||||
<!-- The title can also be in single quotes or in parentheses, or omitted
|
The title can also be in single quotes or in parentheses, or omitted
|
||||||
entirely. The references can be anywhere in your document and the reference IDs
|
entirely. The references can be anywhere in your document and the reference IDs
|
||||||
can be anything so long as they are unique. -->
|
can be anything so long as they are unique.
|
||||||
|
|
||||||
<!-- There is also "implicit naming" which lets you use the link text as the id -->
|
There is also "implicit naming" which lets you use the link text as the id.
|
||||||
|
|
||||||
[This][] is a link.
|
<pre><code class="highlight">[<span class="nv">This</span>][] is a link.
|
||||||
|
|
||||||
[this]: http://thisisalink.com/
|
[<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
|
||||||
|
|
||||||
<!-- But it's not that commonly used. -->
|
But it's not that commonly used.
|
||||||
|
|
||||||
<!-- Images -->
|
## Images
|
||||||
<!-- Images are done the same way as links but with an exclamation point in front! -->
|
Images are done the same way as links but with an exclamation point in front!
|
||||||
|
|
||||||
|
```markdown
|
||||||
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
|
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
|
||||||
|
```
|
||||||
|
|
||||||
<!-- And reference style works as expected -->
|
And reference style works as expected.
|
||||||
|
|
||||||
![This is the alt-attribute.][myimage]
|
<pre><code class="highlight">![<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>]
|
||||||
|
|
||||||
[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
|
[<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre>
|
||||||
|
## Miscellany
|
||||||
<!-- Miscellany -->
|
### Auto-links
|
||||||
<!-- Auto-links -->
|
|
||||||
|
|
||||||
|
```markdown
|
||||||
<http://testwebsite.com/> is equivalent to
|
<http://testwebsite.com/> is equivalent to
|
||||||
[http://testwebsite.com/](http://testwebsite.com/)
|
[http://testwebsite.com/](http://testwebsite.com/)
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Auto-links for emails -->
|
### Auto-links for emails
|
||||||
|
|
||||||
|
```markdown
|
||||||
<foo@bar.com>
|
<foo@bar.com>
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Escaping characters -->
|
### Escaping characters
|
||||||
|
|
||||||
|
```markdown
|
||||||
I want to type *this text surrounded by asterisks* but I don't want it to be
|
I want to type *this text surrounded by asterisks* but I don't want it to be
|
||||||
in italics, so I do this: \*this text surrounded by asterisks\*.
|
in italics, so I do this: \*this text surrounded by asterisks\*.
|
||||||
|
```
|
||||||
|
|
||||||
<!-- Keyboard keys -->
|
### Keyboard keys
|
||||||
<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys -->
|
|
||||||
|
|
||||||
|
In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys.
|
||||||
|
|
||||||
|
```markdown
|
||||||
Your computer crashed? Try sending a
|
Your computer crashed? Try sending a
|
||||||
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||||
|
```
|
||||||
|
### Tables
|
||||||
|
|
||||||
<!-- Tables -->
|
Tables are only available in Github Flavored Markdown and are slightly
|
||||||
<!-- Tables are only available in Github Flavored Markdown and are slightly
|
cumbersome, but if you really want it:
|
||||||
cumbersome, but if you really want it: -->
|
|
||||||
|
|
||||||
|
```markdown
|
||||||
| Col1 | Col2 | Col3 |
|
| Col1 | Col2 | Col3 |
|
||||||
| :----------- | :------: | ------------: |
|
| :----------- | :------: | ------------: |
|
||||||
| Left-aligned | Centered | Right-aligned |
|
| Left-aligned | Centered | Right-aligned |
|
||||||
| blah | blah | blah |
|
| blah | blah | blah |
|
||||||
|
```
|
||||||
|
or, for the same results
|
||||||
|
|
||||||
<!-- or, for the same results -->
|
```markdown
|
||||||
|
|
||||||
Col 1 | Col2 | Col3
|
Col 1 | Col2 | Col3
|
||||||
:-- | :-: | --:
|
:-- | :-: | --:
|
||||||
Ugh this is so ugly | make it | stop
|
Ugh this is so ugly | make it | stop
|
||||||
|
|
||||||
<!-- The end! -->
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
||||||
|
@ -15,6 +15,7 @@ If you have any feedback please feel free to reach me at
|
|||||||
[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
|
[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
|
||||||
|
|
||||||
```matlab
|
```matlab
|
||||||
|
%% Code sections start with two percent signs. Section titles go on the same line.
|
||||||
% Comments start with a percent sign.
|
% Comments start with a percent sign.
|
||||||
|
|
||||||
%{
|
%{
|
||||||
@ -72,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
|
|||||||
|
|
||||||
% Calling functions can be done in either of two ways:
|
% Calling functions can be done in either of two ways:
|
||||||
% Standard function syntax:
|
% Standard function syntax:
|
||||||
load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
|
load('myFile.mat', 'y') % arguments within parentheses, separated by commas
|
||||||
% Command syntax:
|
% Command syntax:
|
||||||
load myFile.mat y % no parentheses, and spaces instead of commas
|
load myFile.mat y % no parentheses, and spaces instead of commas
|
||||||
% Note the lack of quote marks in command form: inputs are always passed as
|
% Note the lack of quote marks in command form: inputs are always passed as
|
||||||
@ -123,6 +124,7 @@ x(2:end) % ans = 32 53 7 1
|
|||||||
x = [4; 32; 53; 7; 1] % Column vector
|
x = [4; 32; 53; 7; 1] % Column vector
|
||||||
|
|
||||||
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
|
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
|
||||||
|
x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9
|
||||||
|
|
||||||
% Matrices
|
% Matrices
|
||||||
A = [1 2 3; 4 5 6; 7 8 9]
|
A = [1 2 3; 4 5 6; 7 8 9]
|
||||||
@ -205,6 +207,8 @@ transpose(A) % Transpose the matrix, which is the same as:
|
|||||||
A one
|
A one
|
||||||
ctranspose(A) % Hermitian transpose the matrix
|
ctranspose(A) % Hermitian transpose the matrix
|
||||||
% (the transpose, followed by taking complex conjugate of each element)
|
% (the transpose, followed by taking complex conjugate of each element)
|
||||||
|
A' % Concise version of complex transpose
|
||||||
|
A.' % Concise version of transpose (without taking complex conjugate)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -254,6 +258,8 @@ axis equal % Set aspect ratio so data units are the same in every direction
|
|||||||
|
|
||||||
scatter(x, y); % Scatter-plot
|
scatter(x, y); % Scatter-plot
|
||||||
hist(x); % Histogram
|
hist(x); % Histogram
|
||||||
|
stem(x); % Plot values as stems, useful for displaying discrete data
|
||||||
|
bar(x); % Plot bar graph
|
||||||
|
|
||||||
z = sin(x);
|
z = sin(x);
|
||||||
plot3(x,y,z); % 3D line plot
|
plot3(x,y,z); % 3D line plot
|
||||||
@ -262,7 +268,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value
|
|||||||
contour(A) % Contour plot of matrix
|
contour(A) % Contour plot of matrix
|
||||||
mesh(A) % Plot as a mesh surface
|
mesh(A) % Plot as a mesh surface
|
||||||
|
|
||||||
h = figure % Create new figure object, with handle h
|
h = figure % Create new figure object, with handle h
|
||||||
figure(h) % Makes the figure corresponding to handle h the current figure
|
figure(h) % Makes the figure corresponding to handle h the current figure
|
||||||
close(h) % close figure with handle h
|
close(h) % close figure with handle h
|
||||||
close all % close all open figure windows
|
close all % close all open figure windows
|
||||||
@ -273,7 +279,7 @@ clf clear % clear current figure window, and reset most figure properties
|
|||||||
|
|
||||||
% Properties can be set and changed through a figure handle.
|
% Properties can be set and changed through a figure handle.
|
||||||
% You can save a handle to a figure when you create it.
|
% You can save a handle to a figure when you create it.
|
||||||
% The function gcf returns a handle to the current figure
|
% The function get returns a handle to the current figure
|
||||||
h = plot(x, y); % you can save a handle to a figure when you create it
|
h = plot(x, y); % you can save a handle to a figure when you create it
|
||||||
set(h, 'Color', 'r')
|
set(h, 'Color', 'r')
|
||||||
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
|
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
|
||||||
@ -400,7 +406,7 @@ exp(x)
|
|||||||
sqrt(x)
|
sqrt(x)
|
||||||
log(x)
|
log(x)
|
||||||
log10(x)
|
log10(x)
|
||||||
abs(x)
|
abs(x) %If x is complex, returns magnitude
|
||||||
min(x)
|
min(x)
|
||||||
max(x)
|
max(x)
|
||||||
ceil(x)
|
ceil(x)
|
||||||
@ -411,6 +417,14 @@ rand % Uniformly distributed pseudorandom numbers
|
|||||||
randi % Uniformly distributed pseudorandom integers
|
randi % Uniformly distributed pseudorandom integers
|
||||||
randn % Normally distributed pseudorandom numbers
|
randn % Normally distributed pseudorandom numbers
|
||||||
|
|
||||||
|
%Complex math operations
|
||||||
|
abs(x) % Magnitude of complex variable x
|
||||||
|
phase(x) % Phase (or angle) of complex variable x
|
||||||
|
real(x) % Returns the real part of x (i.e returns a if x = a +jb)
|
||||||
|
imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb)
|
||||||
|
conj(x) % Returns the complex conjugate
|
||||||
|
|
||||||
|
|
||||||
% Common constants
|
% Common constants
|
||||||
pi
|
pi
|
||||||
NaN
|
NaN
|
||||||
@ -460,11 +474,14 @@ length % length of a vector
|
|||||||
sort % sort in ascending order
|
sort % sort in ascending order
|
||||||
sum % sum of elements
|
sum % sum of elements
|
||||||
prod % product of elements
|
prod % product of elements
|
||||||
mode % modal value
|
mode % modal value
|
||||||
median % median value
|
median % median value
|
||||||
mean % mean value
|
mean % mean value
|
||||||
std % standard deviation
|
std % standard deviation
|
||||||
perms(x) % list all permutations of elements of x
|
perms(x) % list all permutations of elements of x
|
||||||
|
find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators,
|
||||||
|
% i.e. find( x == 3 ) returns indexes of elements that are equal to 3
|
||||||
|
% i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3
|
||||||
|
|
||||||
|
|
||||||
% Classes
|
% Classes
|
||||||
|
588
ms-my/javascript-my.html.markdown
Normal file
588
ms-my/javascript-my.html.markdown
Normal file
@ -0,0 +1,588 @@
|
|||||||
|
---
|
||||||
|
language: javascript
|
||||||
|
contributors:
|
||||||
|
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
|
||||||
|
- ["Ariel Krakowski", "http://www.learneroo.com"]
|
||||||
|
filename: javascript-ms.js
|
||||||
|
translators:
|
||||||
|
- ["abdalim", "https://github.com/abdalim"]
|
||||||
|
lang: ms-my
|
||||||
|
---
|
||||||
|
|
||||||
|
Javascript dicipta oleh Brendan Eich dari Netscape pada 1995. Pada awalnya, ia
|
||||||
|
dicipta sebagai bahasa skrip yang ringkas untuk laman web, melengkapi penggunaan
|
||||||
|
Java untuk aplikasi web yang lebih rumit, namun begitu, integrasi rapat pada
|
||||||
|
halaman web dan sokongan tersedia dalam pelayar web telah menyebabkan ia menjadi
|
||||||
|
lebih kerap digunakan berbanding Java pada bahagian hadapan laman web.
|
||||||
|
|
||||||
|
Namun begitu, Javascript tidak terhad pada pelayar web; Node.js, sebuah projek
|
||||||
|
yang menyediakan 'runtime' berdiri sendiri untuk enjin V8 Google Chrome sedang
|
||||||
|
kian mendapat sambutan yang hangat.
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Komentar adalah seperti dalam C. Komentar sebaris bermula dengan dua sengkang
|
||||||
|
/* dan komentar banyak baris bermula dengan sengkang-bintang
|
||||||
|
dan berakhir dengan bintang-sengkang */
|
||||||
|
|
||||||
|
// Pernyataan boleh ditamatkan dengan ';'
|
||||||
|
doStuff();
|
||||||
|
|
||||||
|
// ... tetapi ia tidak wajib, kerana koma bertitik secara automatik akan
|
||||||
|
// dimasukkan dimana tempat yang ada baris baru, kecuali dalam kes - kes
|
||||||
|
// tertentu.
|
||||||
|
doStuff()
|
||||||
|
|
||||||
|
// Disebabkan kes - kes itu boleh menyebabkan hasil yang tidak diduga, kami
|
||||||
|
// akan sentiasa menggunakan koma bertitik dalam panduan ini.
|
||||||
|
|
||||||
|
///////////////////////////////////
|
||||||
|
// 1. Nombor, String dan Operator
|
||||||
|
|
||||||
|
// Javascript mempunyai satu jenis nombor (iaitu 64-bit IEEE 754 double).
|
||||||
|
// Double mempunyai 52-bit mantissa, iaitu ia cukup untuk menyimpan integer
|
||||||
|
// sehingga 9✕10¹⁵ secara tepatnya.
|
||||||
|
3; // = 3
|
||||||
|
1.5; // = 1.5
|
||||||
|
|
||||||
|
// Sebahagian aritmetic asas berfungsi seperti yang anda jangkakan.
|
||||||
|
1 + 1; // = 2
|
||||||
|
0.1 + 0.2; // = 0.30000000000000004
|
||||||
|
8 - 1; // = 7
|
||||||
|
10 * 2; // = 20
|
||||||
|
35 / 5; // = 7
|
||||||
|
|
||||||
|
// Termasuk pembahagian tidak rata.
|
||||||
|
5 / 2; // = 2.5
|
||||||
|
|
||||||
|
// Dan pembahagian modulo.
|
||||||
|
10 % 2; // = 0
|
||||||
|
30 % 4; // = 2
|
||||||
|
18.5 % 7; // = 4.5
|
||||||
|
|
||||||
|
// Operasi bitwise juga boleh digunakan; bila anda melakukan operasi bitwise,
|
||||||
|
// float anda akan ditukarkan kepada int bertanda *sehingga* 32 bit.
|
||||||
|
1 << 2; // = 4
|
||||||
|
|
||||||
|
// Keutamaan ditekankan menggunakan kurungan.
|
||||||
|
(1 + 3) * 2; // = 8
|
||||||
|
|
||||||
|
// Terdapat tiga nilai nombor-tidak-nyata istimewa
|
||||||
|
Infinity; // hasil operasi seperti 1/0
|
||||||
|
-Infinity; // hasil operasi seperti -1/0
|
||||||
|
NaN; // hasil operasi seperti 0/0, bermaksud 'Bukan Sebuah Nombor'
|
||||||
|
|
||||||
|
// Terdapat juga jenis boolean
|
||||||
|
true;
|
||||||
|
false;
|
||||||
|
|
||||||
|
// Talian dicipta dengan ' atau ''.
|
||||||
|
'abc';
|
||||||
|
"Hello, world";
|
||||||
|
|
||||||
|
// Penafian menggunakan simbol !
|
||||||
|
!true; // = tidak benar
|
||||||
|
!false; // = benar
|
||||||
|
|
||||||
|
// Sama ialah ===
|
||||||
|
1 === 1; // = benar
|
||||||
|
2 === 1; // = tidak benar
|
||||||
|
|
||||||
|
// Tidak sama ialah !==
|
||||||
|
1 !== 1; // = tidak benar
|
||||||
|
2 !== 1; // = benar
|
||||||
|
|
||||||
|
// Lagi perbandingan
|
||||||
|
1 < 10; // = benar
|
||||||
|
1 > 10; // = tidak benar
|
||||||
|
2 <= 2; // = benar
|
||||||
|
2 >= 2; // = benar
|
||||||
|
|
||||||
|
// Talian disambungkan dengan +
|
||||||
|
"Hello " + "world!"; // = "Hello world!"
|
||||||
|
|
||||||
|
// dan dibandingkan dengan < dan >
|
||||||
|
"a" < "b"; // = benar
|
||||||
|
|
||||||
|
// Paksaan jenis dilakukan untuk perbandingan menggunakan dua sama dengan...
|
||||||
|
"5" == 5; // = benar
|
||||||
|
null == undefined; // = benar
|
||||||
|
|
||||||
|
// ...melainkan anda menggunakan ===
|
||||||
|
"5" === 5; // = tidak benar
|
||||||
|
null === undefined; // = tidak benar
|
||||||
|
|
||||||
|
// ...yang boleh menghasilkan keputusan yang pelik...
|
||||||
|
13 + !0; // 14
|
||||||
|
"13" + !0; // '13true'
|
||||||
|
|
||||||
|
// Anda boleh akses huruf dalam perkataan dengan `charAt`
|
||||||
|
"This is a string".charAt(0); // = 'T'
|
||||||
|
|
||||||
|
// ...atau menggunakan `substring` untuk mendapatkan bahagian yang lebih besar.
|
||||||
|
"Hello world".substring(0, 5); // = "Hello"
|
||||||
|
|
||||||
|
// `length` adalah ciri, maka jangan gunakan ().
|
||||||
|
"Hello".length; // = 5
|
||||||
|
|
||||||
|
// Selain itu, terdapat juga `null` dan `undefined`.
|
||||||
|
null; // digunakan untuk menandakan bukan-nilai yang disengajakan
|
||||||
|
undefined; // digunakan untuk menandakan nilai yang tidak wujud pada waktu ini (walaupun `undefined` adalah nilai juga)
|
||||||
|
|
||||||
|
// false, null, undefined, NaN, 0 dan "" adalah tidak benar; semua selain itu adalah benar.
|
||||||
|
// Peringatan, 0 adalah tidak benar dan "0" adalah benar, walaupun 0 == "0".
|
||||||
|
|
||||||
|
///////////////////////////////////
|
||||||
|
// 2. Pembolehubah, Array dan Objek
|
||||||
|
|
||||||
|
// Pembolehubah digunakan dengan kata kunci 'var'. Javascript ialah sebuah
|
||||||
|
// bahasa aturcara yang jenisnya dinamik, maka anda tidak perlu spesifikasikan
|
||||||
|
// jenis pembolehubah. Penetapan menggunakan satu '=' karakter.
|
||||||
|
var someVar = 5;
|
||||||
|
|
||||||
|
// jika anda tinggalkan kata kunci var, anda tidak akan dapat ralat...
|
||||||
|
someOtherVar = 10;
|
||||||
|
|
||||||
|
// ...tetapi pembolehubah anda akan dicipta di dalam skop global, bukan di
|
||||||
|
// dalam skop anda menciptanya.
|
||||||
|
|
||||||
|
// Pembolehubah yang dideklarasikan tanpa ditetapkan sebarang nilai akan
|
||||||
|
// ditetapkan kepada undefined.
|
||||||
|
var someThirdVar; // = undefined
|
||||||
|
|
||||||
|
// jika anda ingin mendeklarasikan beberapa pembolehubah, maka anda boleh
|
||||||
|
// menggunakan koma sebagai pembahagi
|
||||||
|
var someFourthVar = 2, someFifthVar = 4;
|
||||||
|
|
||||||
|
// Terdapat cara mudah untuk melakukan operasi - operasi matematik pada
|
||||||
|
// pembolehubah:
|
||||||
|
someVar += 5; // bersamaan dengan someVar = someVar +5; someVar sama dengan 10 sekarang
|
||||||
|
someVar *= 10; // sekarang someVar bernilai 100
|
||||||
|
|
||||||
|
// dan cara lebih mudah untuk penambahan atau penolakan 1
|
||||||
|
someVar++; // sekarang someVar ialah 101
|
||||||
|
someVar--; // kembali kepada 100
|
||||||
|
|
||||||
|
// Array adalah senarai nilai yang tersusun, yang boleh terdiri daripada
|
||||||
|
// pembolehubah pelbagai jenis.
|
||||||
|
var myArray = ["Hello", 45, true];
|
||||||
|
|
||||||
|
// Setiap ahli array boleh diakses menggunakan syntax kurungan-petak.
|
||||||
|
// Indeks array bermula pada sifar.
|
||||||
|
myArray[1]; // = 45
|
||||||
|
|
||||||
|
// Array boleh diubah dan mempunyai panjang yang tidak tetap dan boleh ubah.
|
||||||
|
myArray.push("World");
|
||||||
|
myArray.length; // = 4
|
||||||
|
|
||||||
|
// Tambah/Ubah di index yang spesifik
|
||||||
|
myArray[3] = "Hello";
|
||||||
|
|
||||||
|
// Objek javascript adalah sama dengan "dictionaries" atau "maps" dalam bahasa
|
||||||
|
// aturcara yang lain: koleksi pasangan kunci-nilai yang tidak mempunyai
|
||||||
|
// sebarang susunan.
|
||||||
|
var myObj = {key1: "Hello", key2: "World"};
|
||||||
|
|
||||||
|
// Kunci adalah string, tetapi 'quote' tidak diperlukan jika ia adalah pengecam
|
||||||
|
// javascript yang sah. Nilai boleh mempunyai sebarang jenis.
|
||||||
|
var myObj = {myKey: "myValue", "my other key": 4};
|
||||||
|
|
||||||
|
// Ciri - ciri objek boleh juga diakses menggunakan syntax subskrip (kurungan-
|
||||||
|
// petak),
|
||||||
|
myObj["my other key"]; // = 4
|
||||||
|
|
||||||
|
// ... atau menggunakan syntax titik, selagi kuncinya adalah pengecam yang sah.
|
||||||
|
myObj.myKey; // = "myValue"
|
||||||
|
|
||||||
|
// Objek adalah boleh diubah; nilai boleh diubah dan kunci baru boleh ditambah.
|
||||||
|
myObj.myThirdKey = true;
|
||||||
|
|
||||||
|
// Jika anda cuba untuk akses nilai yang belum ditetapkan, anda akan mendapat
|
||||||
|
// undefined.
|
||||||
|
myObj.myFourthKey; // = undefined
|
||||||
|
|
||||||
|
///////////////////////////////////
|
||||||
|
// 3. Logik dan Struktur Kawalan
|
||||||
|
|
||||||
|
// Syntax untuk bahagian ini adalah hampir sama dengan Java.
|
||||||
|
|
||||||
|
// Struktur `if` berfungsi seperti yang anda jangkakan.
|
||||||
|
var count = 1;
|
||||||
|
if (count == 3){
|
||||||
|
// dinilai jika count ialah 3
|
||||||
|
} else if (count == 4){
|
||||||
|
// dinilai jika count ialah 4
|
||||||
|
} else {
|
||||||
|
// dinilai jika count bukan 3 atau 4
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sama juga dengan `while`.
|
||||||
|
while (true){
|
||||||
|
// Sebuah ulangan yang tidak terhingga!
|
||||||
|
// An infinite loop!
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ulangan do-while adalah sama dengan ulangan while, kecuali ia akan diulang
|
||||||
|
// sekurang-kurangnya sekali.
|
||||||
|
var input;
|
||||||
|
do {
|
||||||
|
input = getInput();
|
||||||
|
} while (!isValid(input))
|
||||||
|
|
||||||
|
// Ulangan `for` adalah sama dengan C dan Java:
|
||||||
|
// Persiapan; kondisi untuk bersambung; pengulangan.
|
||||||
|
for (var i = 0; i < 5; i++){
|
||||||
|
// akan berulang selama 5 kali
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pernyataan ulangan For/In akan mengulang setiap ciri seluruh jaringan
|
||||||
|
// 'prototype'
|
||||||
|
var description = "";
|
||||||
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
|
for (var x in person){
|
||||||
|
description += person[x] + " ";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Jika anda cuma mahu mengambil kira ciri - ciri yang ditambah pada objek it
|
||||||
|
// sendiri dan bukan 'prototype'nya, sila gunakan semakan hasOwnProperty()
|
||||||
|
var description = "";
|
||||||
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
|
for (var x in person){
|
||||||
|
if (person.hasOwnProperty(x)){
|
||||||
|
description += person[x] + " ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// for/in tidak sepatutnya digunakan untuk mengulang sebuah Array di mana
|
||||||
|
// indeks susunan adalah penting.
|
||||||
|
// Tiada sebarang jaminan bahawa for/in akan mengembalikan indeks dalam
|
||||||
|
// mana - mana susunan
|
||||||
|
|
||||||
|
// && adalah logikal dan, || adalah logikal atau
|
||||||
|
if (house.size == "big" && house.colour == "blue"){
|
||||||
|
house.contains = "bear";
|
||||||
|
}
|
||||||
|
if (colour == "red" || colour == "blue"){
|
||||||
|
// warna adalah sama ada 'red' atau 'blue'
|
||||||
|
}
|
||||||
|
|
||||||
|
// && dan || adalah "lintar pintas", di mana ia berguna untuk menetapkan
|
||||||
|
// nilai asal.
|
||||||
|
var name = otherName || "default";
|
||||||
|
|
||||||
|
|
||||||
|
// Pernyataan `switch` menyemak persamaan menggunakan `===`.
|
||||||
|
// gunakan pernyataan `break` selepas setiap kes
|
||||||
|
// atau tidak, kes - kes selepas kes yang betul akan dijalankan juga.
|
||||||
|
grade = 'B';
|
||||||
|
switch (grade) {
|
||||||
|
case 'A':
|
||||||
|
console.log("Great job");
|
||||||
|
break;
|
||||||
|
case 'B':
|
||||||
|
console.log("OK job");
|
||||||
|
break;
|
||||||
|
case 'C':
|
||||||
|
console.log("You can do better");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.log("Oy vey");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
///////////////////////////////////
|
||||||
|
// 4. Functions, Skop dan Closures
|
||||||
|
|
||||||
|
// Function javascript dideklarasikan dengan kata kunci `function`.
|
||||||
|
function myFunction(thing){
|
||||||
|
return thing.toUpperCase();
|
||||||
|
}
|
||||||
|
myFunction("foo"); // = "FOO"
|
||||||
|
|
||||||
|
// Perhatikan yang nilai yang dikembalikan mesti bermula pada baris yang sama
|
||||||
|
// dengan kata kunci `return`, jika tidak, anda akan sentiasa mengembalikan
|
||||||
|
// `undefined` disebabkan kemasukan 'semicolon' secara automatik. Sila berjaga -
|
||||||
|
// jaga dengan hal ini apabila menggunakan Allman style.
|
||||||
|
function myFunction(){
|
||||||
|
return // <- semicolon dimasukkan secara automatik di sini
|
||||||
|
{thisIsAn: 'object literal'}
|
||||||
|
}
|
||||||
|
myFunction(); // = undefined
|
||||||
|
|
||||||
|
// Function javascript adalah objek kelas pertama, maka ia boleh diberikan
|
||||||
|
// nama pembolehubah yang lain dan diberikan kepada function yang lain sebagai
|
||||||
|
// input - sebagai contoh, apabila membekalkan pengendali event:
|
||||||
|
function myFunction(){
|
||||||
|
// kod ini akan dijalankan selepas 5 saat
|
||||||
|
}
|
||||||
|
setTimeout(myFunction, 5000);
|
||||||
|
// Nota: setTimeout bukan sebahagian daripada bahasa JS, tetapi ia disediakan
|
||||||
|
// oleh pelayar web dan Node.js.
|
||||||
|
|
||||||
|
// Satu lagi function yang disediakan oleh pelayar web adalah setInterval
|
||||||
|
function myFunction(){
|
||||||
|
// kod ini akan dijalankan setiap 5 saat
|
||||||
|
}
|
||||||
|
setInterval(myFunction, 5000);
|
||||||
|
|
||||||
|
// Objek function tidak perlu dideklarasikan dengan nama - anda boleh menulis
|
||||||
|
// function yang tidak bernama didalam input sebuah function lain.
|
||||||
|
setTimeout(function(){
|
||||||
|
// kod ini akan dijalankan dalam 5 saat
|
||||||
|
}, 5000);
|
||||||
|
|
||||||
|
// Javascript mempunyai skop function; function mempunyai skop mereka
|
||||||
|
// tersendiri tetapi blok tidak.
|
||||||
|
if (true){
|
||||||
|
var i = 5;
|
||||||
|
}
|
||||||
|
i; // = 5 - bukan undefined seperti yang anda jangkakan di dalam bahasa blok-skop
|
||||||
|
|
||||||
|
// Ini telah menyebabkan corak biasa iaitu "immediately-executing anonymous
|
||||||
|
// functions", yang mengelakkan pembolehubah sementara daripada bocor ke
|
||||||
|
// skop global.
|
||||||
|
(function(){
|
||||||
|
var temporary = 5;
|
||||||
|
// Kita boleh akses skop global dengan menetapkan nilai ke "objek global",
|
||||||
|
// iaitu dalam pelayar web selalunya adalah `window`. Objek global mungkin
|
||||||
|
// mempunyai nama yang berlainan dalam alam bukan pelayar web seperti Node.js.
|
||||||
|
window.permanent = 10;
|
||||||
|
})();
|
||||||
|
temporary; // akan menghasilkan ralat ReferenceError
|
||||||
|
permanent; // = 10
|
||||||
|
|
||||||
|
// Salah satu ciri terhebat Javascript ialah closure. Jika sebuah function
|
||||||
|
// didefinisikan di dalam sebuah function lain, function yang di dalam akan
|
||||||
|
// mempunyai akses kepada semua pembolehubah function yang di luar, mahupun
|
||||||
|
// selepas function yang di luar tersebut selesai.
|
||||||
|
function sayHelloInFiveSeconds(name){
|
||||||
|
var prompt = "Hello, " + name + "!";
|
||||||
|
// Function dalam diletakkan di dalam skop lokal secara asal, seperti
|
||||||
|
// ia dideklarasikan dengan `var`.
|
||||||
|
function inner(){
|
||||||
|
alert(prompt);
|
||||||
|
}
|
||||||
|
setTimeout(inner, 5000);
|
||||||
|
// setTimeout adalah tak segerak atau asinkroni, maka function sayHelloInFiveSeconds akan selesai serta merta, dan setTimeout akan memanggil
|
||||||
|
// inner selepas itu. Walaubagaimanapun, disebabkan inner terletak didalam
|
||||||
|
// sayHelloInFiveSeconds, inner tetap mempunyai akses kepada pembolehubah
|
||||||
|
// `prompt` apabila ia dipanggil.
|
||||||
|
}
|
||||||
|
sayHelloInFiveSeconds("Adam"); // akan membuka sebuah popup dengan "Hello, Adam!" selepas 5s
|
||||||
|
|
||||||
|
///////////////////////////////////
|
||||||
|
// 5. Lagi tentang Objek, Constructor dan Prototype
|
||||||
|
|
||||||
|
// Objek boleh mengandungi function.
|
||||||
|
var myObj = {
|
||||||
|
myFunc: function(){
|
||||||
|
return "Hello world!";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
myObj.myFunc(); // = "Hello world!"
|
||||||
|
|
||||||
|
// Apabila function sesebuah object dipanggil, ia boleh mengakses objek asalnya
|
||||||
|
// dengan menggunakan kata kunci `this`.
|
||||||
|
myObj = {
|
||||||
|
myString: "Hello world!",
|
||||||
|
myFunc: function(){
|
||||||
|
return this.myString;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
myObj.myFunc(); // = "Hello world!"
|
||||||
|
|
||||||
|
// Nilai sebenar yang ditetapkan kepada this akan ditentukan oleh bagaimana
|
||||||
|
// sesebuah function itu dipanggil, bukan dimana ia didefinisikan. Oleh it,
|
||||||
|
// sesebuah function tidak akan berfungsi jika ia dipanggil bukan pada konteks
|
||||||
|
// objeknya.
|
||||||
|
var myFunc = myObj.myFunc;
|
||||||
|
myFunc(); // = undefined
|
||||||
|
|
||||||
|
// Sebaliknya, sebuah function boleh ditetapkan kepada objek dan mendapat akses
|
||||||
|
// kepada objek itu melalui `this`, walaupun ia tidak ditetapkan semasa ia
|
||||||
|
// didefinisikan.
|
||||||
|
var myOtherFunc = function(){
|
||||||
|
return this.myString.toUpperCase();
|
||||||
|
}
|
||||||
|
myObj.myOtherFunc = myOtherFunc;
|
||||||
|
myObj.myOtherFunc(); // = "HELLO WORLD!"
|
||||||
|
|
||||||
|
// Kita juga boleh menentukan konteks untuk sebuah function dijalankan apabila
|
||||||
|
// ia dipanggil menggunakan `call` atau `apply`.
|
||||||
|
|
||||||
|
var anotherFunc = function(s){
|
||||||
|
return this.myString + s;
|
||||||
|
}
|
||||||
|
anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
|
||||||
|
|
||||||
|
// Function `apply` adalah hampir sama, tetapi ia mengambil sebuah array
|
||||||
|
// sebagai senarai input.
|
||||||
|
|
||||||
|
anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
|
||||||
|
|
||||||
|
// Ini sangat berguna apabila menggunakan sebuah function yang menerima senarai
|
||||||
|
// input dan anda mahu menggunakan sebuah array sebagai input.
|
||||||
|
|
||||||
|
Math.min(42, 6, 27); // = 6
|
||||||
|
Math.min([42, 6, 27]); // = NaN (uh-oh!)
|
||||||
|
Math.min.apply(Math, [42, 6, 27]); // = 6
|
||||||
|
|
||||||
|
// Tetapi, `call` dan `apply` adalah hanya sementara, sebagaimana hidup ini.
|
||||||
|
// Apabila kita mahu ia kekal, kita boleh menggunakan `bind`.
|
||||||
|
|
||||||
|
var boundFunc = anotherFunc.bind(myObj);
|
||||||
|
boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
|
||||||
|
|
||||||
|
// `bind` boleh juga digunakan untuk menggunakan sebuah function tidak
|
||||||
|
// sepenuhnya (curry).
|
||||||
|
|
||||||
|
var product = function(a, b){ return a * b; }
|
||||||
|
var doubler = product.bind(this, 2);
|
||||||
|
doubler(8); // = 16
|
||||||
|
|
||||||
|
// Apabila anda memanggil sebuah function dengan kata kunci `new`, sebuah
|
||||||
|
// objek baru akan dicipta dan dijadikan tersedia kepada function itu melalui
|
||||||
|
// kata kunci `this`. Function yang direka bentuk untuk dipanggil sebegitu rupa
|
||||||
|
// dikenali sebagai constructors.
|
||||||
|
|
||||||
|
var MyConstructor = function(){
|
||||||
|
this.myNumber = 5;
|
||||||
|
}
|
||||||
|
myNewObj = new MyConstructor(); // = {myNumber: 5}
|
||||||
|
myNewObj.myNumber; // = 5
|
||||||
|
|
||||||
|
// Setiap objek JavaScript mempunyai `prototype`. Apabila anda akses sesuatu
|
||||||
|
// ciri sebuah objek yang tidak wujud dalam objek sebenar itu, interpreter akan
|
||||||
|
// mencari ciri itu didalam `prototype`nya.
|
||||||
|
|
||||||
|
// Sebahagian implementasi JS membenarkan anda untuk akses prototype sebuah
|
||||||
|
// objek pada ciri istimewa `__proto__`. Walaupun ini membantu dalam menerangkan
|
||||||
|
// mengenai prototypes, ia bukan sebahagian dari piawai; kita akan melihat
|
||||||
|
// cara - cara piawai untuk menggunakan prototypes nanti.
|
||||||
|
var myObj = {
|
||||||
|
myString: "Hello world!"
|
||||||
|
};
|
||||||
|
var myPrototype = {
|
||||||
|
meaningOfLife: 42,
|
||||||
|
myFunc: function(){
|
||||||
|
return this.myString.toLowerCase()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
myObj.__proto__ = myPrototype;
|
||||||
|
myObj.meaningOfLife; // = 42
|
||||||
|
|
||||||
|
// Ini berfungsi untuk function juga.
|
||||||
|
myObj.myFunc(); // = "hello world!"
|
||||||
|
|
||||||
|
// Sudah pasti, jika ciri anda bukan pada prototype anda, prototype kepada
|
||||||
|
// prototype anda akan disemak, dan seterusnya.
|
||||||
|
myPrototype.__proto__ = {
|
||||||
|
myBoolean: true
|
||||||
|
};
|
||||||
|
myObj.myBoolean; // = true
|
||||||
|
|
||||||
|
// Tiada penyalinan terlibat disini; setiap objek menyimpan rujukan kepada
|
||||||
|
// prototypenya sendiri. Ini bermaksud, kita boleh mengubah prototypenya dan
|
||||||
|
// pengubahsuaian itu akan dilihat dan berkesan dimana sahaja.
|
||||||
|
myPrototype.meaningOfLife = 43;
|
||||||
|
myObj.meaningOfLife; // = 43
|
||||||
|
|
||||||
|
// Kami menyatakan yang `__proto__` adalah bukan piawai, dan tiada cara rasmi
|
||||||
|
// untuk mengubah prototype sesebuah objek. Walaubagaimanapun, terdapat dua
|
||||||
|
// cara untuk mencipta objek baru dengan sesebuah prototype.
|
||||||
|
|
||||||
|
// Yang pertama ialah Object.create, yang merupakan tambahan terbaru pada JS,
|
||||||
|
// dan oleh itu tiada dalam semua implementasi buat masa ini.
|
||||||
|
var myObj = Object.create(myPrototype);
|
||||||
|
myObj.meaningOfLife; // = 43
|
||||||
|
|
||||||
|
// Cara kedua, yang boleh digunakan dimana sahaja, adalah berkaitan dengan
|
||||||
|
// constructor. Constructors mempunyai sebuah ciri yang dipanggil prototype.
|
||||||
|
// Ini *bukan* prototype constructor terbabit; tetapi, ia adalah prototype yang
|
||||||
|
// diberikan kepada objek baru apabila ia dicipta menggunakan constructor dan
|
||||||
|
// kata kunci new.
|
||||||
|
MyConstructor.prototype = {
|
||||||
|
myNumber: 5,
|
||||||
|
getMyNumber: function(){
|
||||||
|
return this.myNumber;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var myNewObj2 = new MyConstructor();
|
||||||
|
myNewObj2.getMyNumber(); // = 5
|
||||||
|
myNewObj2.myNumber = 6
|
||||||
|
myNewObj2.getMyNumber(); // = 6
|
||||||
|
|
||||||
|
// Jenis yang terbina sedia seperti string dan nombor juga mempunyai constructor
|
||||||
|
// yang mencipta objek pembalut yang serupa.
|
||||||
|
var myNumber = 12;
|
||||||
|
var myNumberObj = new Number(12);
|
||||||
|
myNumber == myNumberObj; // = true
|
||||||
|
|
||||||
|
// Kecuali, mereka sebenarnya tak sama sepenuhnya.
|
||||||
|
typeof myNumber; // = 'number'
|
||||||
|
typeof myNumberObj; // = 'object'
|
||||||
|
myNumber === myNumberObj; // = false
|
||||||
|
if (0){
|
||||||
|
// Kod ini tidak akan dilaksanakan, kerana 0 adalah tidak benar.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walaubagaimanapun, pembalut objek dan jenis terbina yang biasa berkongsi
|
||||||
|
// prototype, maka sebagai contoh, anda sebenarnya boleh menambah fungsi
|
||||||
|
// kepada string.
|
||||||
|
String.prototype.firstCharacter = function(){
|
||||||
|
return this.charAt(0);
|
||||||
|
}
|
||||||
|
"abc".firstCharacter(); // = "a"
|
||||||
|
|
||||||
|
// Fakta ini selalu digunakan dalam "polyfilling", iaitu melaksanakan fungsi
|
||||||
|
// baru JavaScript didalam subset JavaScript yang lama, supaya ia boleh
|
||||||
|
// digunakan di dalam persekitaran yang lama seperti pelayar web yang lama.
|
||||||
|
|
||||||
|
// Sebagai contoh, kami menyatakan yang Object.create belum lagi tersedia
|
||||||
|
// di semua implementasi, tetapi kita masih boleh menggunakannya dengan polyfill:
|
||||||
|
if (Object.create === undefined){ // jangan ganti jika ia sudah wujud
|
||||||
|
Object.create = function(proto){
|
||||||
|
// buat satu constructor sementara dengan prototype yang betul
|
||||||
|
var Constructor = function(){};
|
||||||
|
Constructor.prototype = proto;
|
||||||
|
// kemudian gunakannya untuk mencipta objek baru yang diberikan
|
||||||
|
// prototype yang betul
|
||||||
|
return new Constructor();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
## Bacaan Lanjut
|
||||||
|
|
||||||
|
[Mozilla Developer Network][1] menyediakan dokumentasi yang sangat baik untuk
|
||||||
|
JavaScript kerana ia digunakan di dalam pelayar - pelayar web. Tambahan pula,
|
||||||
|
ia adalah sebuah wiki, maka, sambil anda belajar lebih banyak lagi, anda boleh
|
||||||
|
membantu orang lain dengan berkongsi pengetahuan anda.
|
||||||
|
|
||||||
|
[A re-introduction to JavaScript][2] oleh MDN meliputi semua konsep yang
|
||||||
|
diterangkan di sini dengan lebih terperinci. Panduan ini menerangkan bahasa
|
||||||
|
aturcara JavaScript dengan agak mudah; jika anda mahu belajar lebih lanjut
|
||||||
|
tentang menggunakan JavaScript didalam laman web, mulakan dengan mempelajari
|
||||||
|
tentang [Document Object Model][3].
|
||||||
|
|
||||||
|
[Learn Javascript by Example and with Challenges][4] adalah variasi panduan ini
|
||||||
|
dengan cabaran yang tersedia pakai.
|
||||||
|
|
||||||
|
[JavaScript Garden][5] pula adalah panduan yang lebih terperinci mengenai
|
||||||
|
semua bahagian bahasa aturcara ini yang bertentangan dengan naluri atau
|
||||||
|
kebiasaan.
|
||||||
|
|
||||||
|
[JavaScript: The Definitive Guide][6] adalah panduan klasik dan buku rujukan.
|
||||||
|
|
||||||
|
Selain daripada penyumbang terus kepada artikel ini, sebahagian kandungannya
|
||||||
|
adalah adaptasi daripada tutorial Python Louie Dinh di dalam laman web ini,
|
||||||
|
dan [JS Tutorial][7] di Mozilla Developer Network.
|
||||||
|
|
||||||
|
|
||||||
|
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
|
||||||
|
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
|
||||||
|
[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
|
||||||
|
[4]: http://www.learneroo.com/modules/64/nodes/350
|
||||||
|
[5]: http://bonsaiden.github.io/JavaScript-Garden/
|
||||||
|
[6]: http://www.amazon.com/gp/product/0596805527/
|
||||||
|
[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
|
102
ms-my/json-my.html.markdown
Normal file
102
ms-my/json-my.html.markdown
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
---
|
||||||
|
language: json
|
||||||
|
filename: learnjson-ms.json
|
||||||
|
contributors:
|
||||||
|
- ["Anna Harren", "https://github.com/iirelu"]
|
||||||
|
- ["Marco Scannadinari", "https://github.com/marcoms"]
|
||||||
|
- ["himanshu", "https://github.com/himanshu81494"]
|
||||||
|
- ["Michael Neth", "https://github.com/infernocloud"]
|
||||||
|
translators:
|
||||||
|
- ["abdalim", "https://github.com/abdalim"]
|
||||||
|
lang: ms-my
|
||||||
|
---
|
||||||
|
|
||||||
|
Disebabkan JSON adalah format pertukaran-data yang sangat ringkas, panduan ini
|
||||||
|
kemungkinan besar adalah Learn X in Y Minutes yang paling mudah.
|
||||||
|
|
||||||
|
JSON dalam bentuk paling aslinya sebenarnya tidak mempunyai sebarang komentar,
|
||||||
|
tetapi kebanyakan pembaca menerima komen dalam bentuk C (`\\`,`/* */`). Beberapa
|
||||||
|
pembaca juga bertoleransi terhadap koma terakhir (iaitu koma selepas elemen
|
||||||
|
terakhir di dalam array atau selepas ciri terakhir sesuatu objek), tetapi semua
|
||||||
|
ini harus dielakkan dan dijauhkan untuk keserasian yang lebih baik.
|
||||||
|
|
||||||
|
Untuk tujuan ini bagaimanapun, semua di dalam panduan ini adalah 100% JSON yang
|
||||||
|
sah. Luckily, it kind of speaks for itself.
|
||||||
|
|
||||||
|
Sebuah nilai JSON harus terdiri dari salah satu, iaitu, nombor, string, array,
|
||||||
|
objek atau salah satu dari nama literal berikut: true, false, null.
|
||||||
|
|
||||||
|
Pelayar web yang menyokong adalah: Firefox 3.5+, Internet Explorer 8.0+, Chrome
|
||||||
|
1.0+, Opera 10.0+, dan Safari 4.0+.
|
||||||
|
|
||||||
|
Sambungan fail untuk fail - fail JSON adalah ".json" dan jenis MIME untuk teks
|
||||||
|
JSON adalah "application/json".
|
||||||
|
|
||||||
|
Banyak bahasa aturcara mempunyai fungsi untuk menyirikan (mengekod) dan
|
||||||
|
menyah-sirikan (men-dekod) data JSON kepada struktur data asal. Javascript
|
||||||
|
mempunyai sokongon tersirat untuk memanipulasi teks JSON sebagai data.
|
||||||
|
|
||||||
|
Maklumat lebih lanjut boleh dijumpai di http://www.json.org/
|
||||||
|
|
||||||
|
JSON dibina pada dua struktur:
|
||||||
|
* Sebuah koleksi pasangan nama/nilai. Di dalam pelbagai bahasa aturcara, ini
|
||||||
|
direalisasikan sebagai objek, rekod, "struct", "dictionary", "hash table",
|
||||||
|
senarai berkunci, atau "associative array".
|
||||||
|
* Sebuah senarai nilai yang tersusun. Dalam kebanyakan bahasa aturcara, ini
|
||||||
|
direalisasikan sebagai array, vektor, senarai atau urutan.
|
||||||
|
|
||||||
|
Sebuah objek dengan pelbagai pasangan nama/nilai.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"kunci": "nilai",
|
||||||
|
|
||||||
|
"kekunci": "harus sentiasa dibalut dengan 'double quotes'",
|
||||||
|
"nombor": 0,
|
||||||
|
"strings": "Hellø, wørld. Semua unicode dibenarkan, bersama \"escaping\".",
|
||||||
|
"ada bools?": true,
|
||||||
|
"tiada apa - apa": null,
|
||||||
|
|
||||||
|
"nombor besar": 1.2e+100,
|
||||||
|
|
||||||
|
"objek": {
|
||||||
|
"komen": "Sebahagian besar struktur akan terdiri daripada objek.",
|
||||||
|
|
||||||
|
"array": [0, 1, 2, 3, "Array boleh mempunyai sebarang jenis data di dalamnya.", 5],
|
||||||
|
|
||||||
|
"objek lain": {
|
||||||
|
"komen": "Objek boleh dibina dengan pelbagai lapisan, sangat berguna."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
"kebendulan": [
|
||||||
|
{
|
||||||
|
"punca potassium": ["pisang"]
|
||||||
|
},
|
||||||
|
[
|
||||||
|
[1, 0, 0, 0],
|
||||||
|
[0, 1, 0, 0],
|
||||||
|
[0, 0, 1, "neo"],
|
||||||
|
[0, 0, 0, 1]
|
||||||
|
]
|
||||||
|
],
|
||||||
|
|
||||||
|
"stail alternatif": {
|
||||||
|
"komen": "cuba lihat ini!"
|
||||||
|
, "posisi koma": "tidak mengapa - selagi ia adalah sebelum nama atau kunci seterusnya, maka ia sah"
|
||||||
|
, "komen lain": "sungguh bagus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Sebuah array sahaja yang mengandungi nilai - nilai juga adalah JSON yang sah.
|
||||||
|
|
||||||
|
```json
|
||||||
|
[1, 2, 3, "text", true]
|
||||||
|
```
|
||||||
|
|
||||||
|
Objek - objek boleh menjadi sebahagian dari array juga.
|
||||||
|
|
||||||
|
```json
|
||||||
|
[{"nama": "Abe", "umur": 25}, {"nama": "Jemah", "umur": 29}, {"name": "Yob", "umur": 31}]
|
||||||
|
```
|
@ -11,7 +11,7 @@ that gives the programmer power without compromises on runtime efficiency.
|
|||||||
|
|
||||||
Nim is efficient, expressive, and elegant.
|
Nim is efficient, expressive, and elegant.
|
||||||
|
|
||||||
```nimrod
|
```javascript
|
||||||
var # Declare (and assign) variables,
|
var # Declare (and assign) variables,
|
||||||
letter: char = 'n' # with or without type annotations
|
letter: char = 'n' # with or without type annotations
|
||||||
lang = "N" & "im"
|
lang = "N" & "im"
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
@ -1,13 +1,12 @@
|
|||||||
---
|
---
|
||||||
|
|
||||||
language: Objective-C
|
language: Objective-C
|
||||||
contributors:
|
contributors:
|
||||||
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
|
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
|
||||||
- ["Yannick Loriot", "https://github.com/YannickL"]
|
- ["Yannick Loriot", "https://github.com/YannickL"]
|
||||||
- ["Levi Bostian", "https://github.com/levibostian"]
|
- ["Levi Bostian", "https://github.com/levibostian"]
|
||||||
- ["Clayton Walker", "https://github.com/cwalk"]
|
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||||
|
- ["Fernando Valverde", "http://visualcosita.xyz"]
|
||||||
filename: LearnObjectiveC.m
|
filename: LearnObjectiveC.m
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
|
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
|
||||||
@ -20,6 +19,10 @@ It is a general-purpose, object-oriented programming language that adds Smalltal
|
|||||||
Multi-line comments look like this
|
Multi-line comments look like this
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// XCode supports pragma mark directive that improve jump bar readability
|
||||||
|
#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions'
|
||||||
|
#pragma mark - Navigation Functions // Same tag, now with a separator
|
||||||
|
|
||||||
// Imports the Foundation headers with #import
|
// Imports the Foundation headers with #import
|
||||||
// Use <> to import global files (in general frameworks)
|
// Use <> to import global files (in general frameworks)
|
||||||
// Use "" to import local files (from project)
|
// Use "" to import local files (from project)
|
||||||
@ -148,13 +151,13 @@ int main (int argc, const char * argv[])
|
|||||||
[mutableDictionary setObject:@"value1" forKey:@"key1"];
|
[mutableDictionary setObject:@"value1" forKey:@"key1"];
|
||||||
[mutableDictionary setObject:@"value2" forKey:@"key2"];
|
[mutableDictionary setObject:@"value2" forKey:@"key2"];
|
||||||
[mutableDictionary removeObjectForKey:@"key1"];
|
[mutableDictionary removeObjectForKey:@"key1"];
|
||||||
|
|
||||||
// Change types from Mutable To Immutable
|
// Change types from Mutable To Immutable
|
||||||
//In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
|
//In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
|
||||||
NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
|
NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
|
||||||
NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
|
NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
|
||||||
|
|
||||||
|
|
||||||
// Set object
|
// Set object
|
||||||
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
|
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
|
||||||
NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order)
|
NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order)
|
||||||
@ -599,6 +602,52 @@ int main (int argc, const char * argv[]) {
|
|||||||
|
|
||||||
@end
|
@end
|
||||||
|
|
||||||
|
// Starting in Xcode 7.0, you can create Generic classes,
|
||||||
|
// allowing you to provide greater type safety and clarity
|
||||||
|
// without writing excessive boilerplate.
|
||||||
|
@interface Result<__covariant A> : NSObject
|
||||||
|
|
||||||
|
- (void)handleSuccess:(void(^)(A))success
|
||||||
|
failure:(void(^)(NSError *))failure;
|
||||||
|
|
||||||
|
@property (nonatomic) A object;
|
||||||
|
|
||||||
|
@end
|
||||||
|
|
||||||
|
// we can now declare instances of this class like
|
||||||
|
Result<NSNumber *> *result;
|
||||||
|
Result<NSArray *> *result;
|
||||||
|
|
||||||
|
// Each of these cases would be equivalent to rewriting Result's interface
|
||||||
|
// and substituting the appropriate type for A
|
||||||
|
@interface Result : NSObject
|
||||||
|
- (void)handleSuccess:(void(^)(NSArray *))success
|
||||||
|
failure:(void(^)(NSError *))failure;
|
||||||
|
@property (nonatomic) NSArray * object;
|
||||||
|
@end
|
||||||
|
|
||||||
|
@interface Result : NSObject
|
||||||
|
- (void)handleSuccess:(void(^)(NSNumber *))success
|
||||||
|
failure:(void(^)(NSError *))failure;
|
||||||
|
@property (nonatomic) NSNumber * object;
|
||||||
|
@end
|
||||||
|
|
||||||
|
// It should be obvious, however, that writing one
|
||||||
|
// Class to solve a problem is always preferable to writing two
|
||||||
|
|
||||||
|
// Note that Clang will not accept generic types in @implementations,
|
||||||
|
// so your @implemnation of Result would have to look like this:
|
||||||
|
|
||||||
|
@implementation Result
|
||||||
|
|
||||||
|
- (void)handleSuccess:(void (^)(id))success
|
||||||
|
failure:(void (^)(NSError *))failure {
|
||||||
|
// Do something
|
||||||
|
}
|
||||||
|
|
||||||
|
@end
|
||||||
|
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Protocols
|
// Protocols
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
@ -5,6 +5,7 @@ language: perl
|
|||||||
filename: learnperl.pl
|
filename: learnperl.pl
|
||||||
contributors:
|
contributors:
|
||||||
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
||||||
|
- ["Dan Book", "http://github.com/Grinnz"]
|
||||||
---
|
---
|
||||||
|
|
||||||
Perl 5 is a highly capable, feature-rich programming language with over 25 years of development.
|
Perl 5 is a highly capable, feature-rich programming language with over 25 years of development.
|
||||||
@ -14,6 +15,15 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f
|
|||||||
```perl
|
```perl
|
||||||
# Single line comments start with a number sign.
|
# Single line comments start with a number sign.
|
||||||
|
|
||||||
|
#### Strict and warnings
|
||||||
|
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
|
||||||
|
# All perl scripts and modules should include these lines. Strict causes
|
||||||
|
# compilation to fail in cases like misspelled variable names, and warnings
|
||||||
|
# will print warning messages in case of common pitfalls like concatenating
|
||||||
|
# to an undefined value.
|
||||||
|
|
||||||
#### Perl variable types
|
#### Perl variable types
|
||||||
|
|
||||||
@ -37,7 +47,9 @@ my @animals = ("camel", "llama", "owl");
|
|||||||
my @numbers = (23, 42, 69);
|
my @numbers = (23, 42, 69);
|
||||||
my @mixed = ("camel", 42, 1.23);
|
my @mixed = ("camel", 42, 1.23);
|
||||||
|
|
||||||
|
# Array elements are accessed using square brackets, with a $ to indicate
|
||||||
|
# one value will be returned.
|
||||||
|
my $second = $animals[1];
|
||||||
|
|
||||||
## Hashes
|
## Hashes
|
||||||
# A hash represents a set of key/value pairs:
|
# A hash represents a set of key/value pairs:
|
||||||
@ -50,11 +62,39 @@ my %fruit_color = (
|
|||||||
apple => "red",
|
apple => "red",
|
||||||
banana => "yellow",
|
banana => "yellow",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
# Hash elements are accessed using curly braces, again with the $ sigil.
|
||||||
|
my $color = $fruit_color{apple};
|
||||||
|
|
||||||
# Scalars, arrays and hashes are documented more fully in perldata.
|
# Scalars, arrays and hashes are documented more fully in perldata.
|
||||||
# (perldoc perldata).
|
# (perldoc perldata).
|
||||||
|
|
||||||
# More complex data types can be constructed using references, which allow you
|
#### References
|
||||||
# to build lists and hashes within lists and hashes.
|
|
||||||
|
# More complex data types can be constructed using references, which allow
|
||||||
|
# you to build arrays and hashes within arrays and hashes.
|
||||||
|
|
||||||
|
my $array_ref = \@array;
|
||||||
|
my $hash_ref = \%hash;
|
||||||
|
my @array_of_arrays = (\@array1, \@array2, \@array3);
|
||||||
|
|
||||||
|
# You can also create anonymous arrays or hashes, returning a reference:
|
||||||
|
|
||||||
|
my $fruits = ["apple", "banana"];
|
||||||
|
my $colors = {apple => "red", banana => "yellow"};
|
||||||
|
|
||||||
|
# References can be dereferenced by prefixing the appropriate sigil.
|
||||||
|
|
||||||
|
my @fruits_array = @$fruits;
|
||||||
|
my %colors_hash = %$colors;
|
||||||
|
|
||||||
|
# As a shortcut, the arrow operator can be used to dereference and access a
|
||||||
|
# single value.
|
||||||
|
|
||||||
|
my $first = $array_ref->[0];
|
||||||
|
my $value = $hash_ref->{banana};
|
||||||
|
|
||||||
|
# See perlreftut and perlref for more in-depth documentation on references.
|
||||||
|
|
||||||
#### Conditional and looping constructs
|
#### Conditional and looping constructs
|
||||||
|
|
||||||
@ -105,6 +145,9 @@ for (@elements) {
|
|||||||
# the Perlish post-condition way again
|
# the Perlish post-condition way again
|
||||||
print for @elements;
|
print for @elements;
|
||||||
|
|
||||||
|
# iterating through the keys and values of a referenced hash
|
||||||
|
print $hash_ref->{$_} for keys %$hash_ref;
|
||||||
|
|
||||||
#### Regular expressions
|
#### Regular expressions
|
||||||
|
|
||||||
# Perl's regular expression support is both broad and deep, and is the subject
|
# Perl's regular expression support is both broad and deep, and is the subject
|
||||||
@ -151,11 +194,101 @@ sub logger {
|
|||||||
# Now we can use the subroutine just as any other built-in function:
|
# Now we can use the subroutine just as any other built-in function:
|
||||||
|
|
||||||
logger("We have a logger subroutine!");
|
logger("We have a logger subroutine!");
|
||||||
|
|
||||||
|
#### Modules
|
||||||
|
|
||||||
|
# A module is a set of Perl code, usually subroutines, which can be used in
|
||||||
|
# other Perl code. It is usually stored in a file with the extension .pm so
|
||||||
|
# that Perl can find it.
|
||||||
|
|
||||||
|
package MyModule;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
|
||||||
|
sub trim {
|
||||||
|
my $string = shift;
|
||||||
|
$string =~ s/^\s+//;
|
||||||
|
$string =~ s/\s+$//;
|
||||||
|
return $string;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# From elsewhere:
|
||||||
|
|
||||||
|
use MyModule;
|
||||||
|
MyModule::trim($string);
|
||||||
|
|
||||||
|
# The Exporter module can help with making subroutines exportable, so they
|
||||||
|
# can be used like this:
|
||||||
|
|
||||||
|
use MyModule 'trim';
|
||||||
|
trim($string);
|
||||||
|
|
||||||
|
# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and
|
||||||
|
# provide a range of features to help you avoid reinventing the wheel. A
|
||||||
|
# number of popular modules like Exporter are included with the Perl
|
||||||
|
# distribution itself. See perlmod for more details on modules in Perl.
|
||||||
|
|
||||||
|
#### Objects
|
||||||
|
|
||||||
|
# Objects in Perl are just references that know which class (package) they
|
||||||
|
# belong to, so that methods (subroutines) called on it can be found there.
|
||||||
|
# The bless function is used in constructors (usually new) to set this up.
|
||||||
|
# However, you never need to call it yourself if you use a module like Moose
|
||||||
|
# or Moo (see below).
|
||||||
|
|
||||||
|
package MyCounter;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
|
||||||
|
sub new {
|
||||||
|
my $class = shift;
|
||||||
|
my $self = {count => 0};
|
||||||
|
return bless $self, $class;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub count {
|
||||||
|
my $self = shift;
|
||||||
|
return $self->{count};
|
||||||
|
}
|
||||||
|
|
||||||
|
sub increment {
|
||||||
|
my $self = shift;
|
||||||
|
$self->{count}++;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# Methods can be called on a class or object instance with the arrow operator.
|
||||||
|
|
||||||
|
use MyCounter;
|
||||||
|
my $counter = MyCounter->new;
|
||||||
|
print $counter->count, "\n"; # 0
|
||||||
|
$counter->increment;
|
||||||
|
print $counter->count, "\n"; # 1
|
||||||
|
|
||||||
|
# The modules Moose and Moo from CPAN can help you set up your object classes.
|
||||||
|
# They provide a constructor and simple syntax for declaring attributes. This
|
||||||
|
# class can be used equivalently to the one above.
|
||||||
|
|
||||||
|
package MyCounter;
|
||||||
|
use Moo; # imports strict and warnings
|
||||||
|
|
||||||
|
has 'count' => (is => 'rwp', default => 0, init_arg => undef);
|
||||||
|
|
||||||
|
sub increment {
|
||||||
|
my $self = shift;
|
||||||
|
$self->_set_count($self->count + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# Object-oriented programming is covered more thoroughly in perlootut, and its
|
||||||
|
# low-level implementation in Perl is covered in perlobj.
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Using Perl modules
|
#### FAQ
|
||||||
|
|
||||||
Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN (http://www.cpan.org/). A number of popular modules are included with the Perl distribution itself.
|
|
||||||
|
|
||||||
perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.
|
perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.
|
||||||
|
|
||||||
|
@ -1,10 +1,9 @@
|
|||||||
---
|
---
|
||||||
name: perl6
|
|
||||||
category: language
|
category: language
|
||||||
language: perl6
|
language: perl6
|
||||||
filename: learnperl6.pl
|
filename: learnperl6.pl
|
||||||
contributors:
|
contributors:
|
||||||
- ["Nami-Doc", "http://github.com/Nami-Doc"]
|
- ["vendethiel", "http://github.com/vendethiel"]
|
||||||
---
|
---
|
||||||
|
|
||||||
Perl 6 is a highly capable, feature-rich programming language made for at
|
Perl 6 is a highly capable, feature-rich programming language made for at
|
||||||
@ -104,7 +103,7 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument
|
|||||||
|
|
||||||
## It can also have optional arguments:
|
## It can also have optional arguments:
|
||||||
sub with-optional($arg?) { # the "?" marks the argument optional
|
sub with-optional($arg?) { # the "?" marks the argument optional
|
||||||
say "I might return `(Any)` (Perl's "null"-like value) if I don't have
|
say "I might return `(Any)` (Perl's 'null'-like value) if I don't have
|
||||||
an argument passed, or I'll return my argument";
|
an argument passed, or I'll return my argument";
|
||||||
$arg;
|
$arg;
|
||||||
}
|
}
|
||||||
@ -374,6 +373,8 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return
|
|||||||
say join(' ', @array[15..*]); #=> 15 16 17 18 19
|
say join(' ', @array[15..*]); #=> 15 16 17 18 19
|
||||||
# which is equivalent to:
|
# which is equivalent to:
|
||||||
say join(' ', @array[-> $n { 15..$n }]);
|
say join(' ', @array[-> $n { 15..$n }]);
|
||||||
|
# Note: if you try to do either of those with an infinite array,
|
||||||
|
# you'll trigger an infinite loop (your program won't finish)
|
||||||
|
|
||||||
# You can use that in most places you'd expect, even assigning to an array
|
# You can use that in most places you'd expect, even assigning to an array
|
||||||
my @numbers = ^20;
|
my @numbers = ^20;
|
||||||
@ -735,7 +736,7 @@ try {
|
|||||||
# You can throw an exception using `die`:
|
# You can throw an exception using `die`:
|
||||||
die X::AdHoc.new(payload => 'Error !');
|
die X::AdHoc.new(payload => 'Error !');
|
||||||
|
|
||||||
# You can access the last exception with `$!` (usually used in a `CATCH` block)
|
# You can access the last exception with `$!` (use `$_` in a `CATCH` block)
|
||||||
|
|
||||||
# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`,
|
# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`,
|
||||||
# which is a kind of "unthrown exception". They're not thrown until you tried to look
|
# which is a kind of "unthrown exception". They're not thrown until you tried to look
|
||||||
@ -763,8 +764,9 @@ try {
|
|||||||
# and `enum`) are actually packages. (Packages are the lowest common denominator)
|
# and `enum`) are actually packages. (Packages are the lowest common denominator)
|
||||||
# Packages are important - especially as Perl is well-known for CPAN,
|
# Packages are important - especially as Perl is well-known for CPAN,
|
||||||
# the Comprehensive Perl Archive Network.
|
# the Comprehensive Perl Archive Network.
|
||||||
# You usually don't use packages directly: you use `class Package::Name::Here;`,
|
# You're not supposed to use the package keyword, usually:
|
||||||
# or if you only want to export variables/subs, you can use `module`:
|
# you use `class Package::Name::Here;` to declare a class,
|
||||||
|
# or if you only want to export variables/subs, you can use `module`:
|
||||||
module Hello::World { # Bracketed form
|
module Hello::World { # Bracketed form
|
||||||
# If `Hello` doesn't exist yet, it'll just be a "stub",
|
# If `Hello` doesn't exist yet, it'll just be a "stub",
|
||||||
# that can be redeclared as something else later.
|
# that can be redeclared as something else later.
|
||||||
@ -774,11 +776,6 @@ unit module Parse::Text; # file-scoped form
|
|||||||
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
|
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
|
||||||
}
|
}
|
||||||
|
|
||||||
# NOTE for Perl 5 users: even though the `package` keyword exists,
|
|
||||||
# the braceless form is invalid (to catch a "perl5ism"). This will error out:
|
|
||||||
# package Foo; # because Perl 6 will think the entire file is Perl 5
|
|
||||||
# Just use `module` or the brace version of `package`.
|
|
||||||
|
|
||||||
# You can use a module (bring its declarations into scope) with `use`
|
# You can use a module (bring its declarations into scope) with `use`
|
||||||
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
|
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
|
||||||
say from-json('[1]').perl; #=> [1]
|
say from-json('[1]').perl; #=> [1]
|
||||||
@ -806,9 +803,8 @@ module Foo::Bar {
|
|||||||
my sub unavailable { # `my sub` is the default
|
my sub unavailable { # `my sub` is the default
|
||||||
say "Can't access me from outside, I'm my !";
|
say "Can't access me from outside, I'm my !";
|
||||||
}
|
}
|
||||||
|
say ++$n; # increment the package variable and output its value
|
||||||
}
|
}
|
||||||
|
|
||||||
say ++$n; # lexically-scoped variables are still available
|
|
||||||
}
|
}
|
||||||
say $Foo::Bar::n; #=> 1
|
say $Foo::Bar::n; #=> 1
|
||||||
Foo::Bar::inc; #=> 2
|
Foo::Bar::inc; #=> 2
|
||||||
@ -870,8 +866,16 @@ LEAVE { say "Runs everytime you leave a block, even when an exception
|
|||||||
|
|
||||||
PRE { say "Asserts a precondition at every block entry,
|
PRE { say "Asserts a precondition at every block entry,
|
||||||
before ENTER (especially useful for loops)" }
|
before ENTER (especially useful for loops)" }
|
||||||
|
# exemple:
|
||||||
|
for 0..2 {
|
||||||
|
PRE { $_ > 1 } # This is going to blow up with "Precondition failed"
|
||||||
|
}
|
||||||
|
|
||||||
POST { say "Asserts a postcondition at every block exit,
|
POST { say "Asserts a postcondition at every block exit,
|
||||||
after LEAVE (especially useful for loops)" }
|
after LEAVE (especially useful for loops)" }
|
||||||
|
for 0..2 {
|
||||||
|
POST { $_ < 2 } # This is going to blow up with "Postcondition failed"
|
||||||
|
}
|
||||||
|
|
||||||
## * Block/exceptions phasers
|
## * Block/exceptions phasers
|
||||||
sub {
|
sub {
|
||||||
@ -1239,14 +1243,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left
|
|||||||
# Group: you can group parts of your regexp with `[]`.
|
# Group: you can group parts of your regexp with `[]`.
|
||||||
# These groups are *not* captured (like PCRE's `(?:)`).
|
# These groups are *not* captured (like PCRE's `(?:)`).
|
||||||
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
|
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
|
||||||
so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
|
so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
|
||||||
# The previous line returns `True`.
|
# The previous line returns `True`.
|
||||||
# We match the "ABC" 1 or more time (the `+` was applied to the group).
|
# We match the "012" 1 or more time (the `+` was applied to the group).
|
||||||
|
|
||||||
# But this does not go far enough, because we can't actually get back what
|
# But this does not go far enough, because we can't actually get back what
|
||||||
# we matched.
|
# we matched.
|
||||||
# Capture: We can actually *capture* the results of the regexp, using parentheses.
|
# Capture: We can actually *capture* the results of the regexp, using parentheses.
|
||||||
so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below)
|
so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below)
|
||||||
|
|
||||||
# So, starting with the grouping explanations.
|
# So, starting with the grouping explanations.
|
||||||
# As we said before, our `Match` object is available as `$/`:
|
# As we said before, our `Match` object is available as `$/`:
|
||||||
@ -1325,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Extra: the MAIN subroutime
|
### Extra: the MAIN subroutine
|
||||||
# The `MAIN` subroutine is called when you run a Perl 6 file directly.
|
# The `MAIN` subroutine is called when you run a Perl 6 file directly.
|
||||||
# It's very powerful, because Perl 6 actually parses the arguments
|
# It's very powerful, because Perl 6 actually parses the arguments
|
||||||
# and pass them as such to the sub. It also handles named argument (`--foo`)
|
# and pass them as such to the sub. It also handles named argument (`--foo`)
|
||||||
|
@ -53,6 +53,8 @@ $int1 = 12; // => 12
|
|||||||
$int2 = -12; // => -12
|
$int2 = -12; // => -12
|
||||||
$int3 = 012; // => 10 (a leading 0 denotes an octal number)
|
$int3 = 012; // => 10 (a leading 0 denotes an octal number)
|
||||||
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
|
$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
|
||||||
|
// Binary integer literals are available since PHP 5.4.0.
|
||||||
|
$int5 = 0b11111111; // 255 (a leading 0b denotes a binary number)
|
||||||
|
|
||||||
// Floats (aka doubles)
|
// Floats (aka doubles)
|
||||||
$float = 1.234;
|
$float = 1.234;
|
||||||
@ -116,11 +118,11 @@ echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
|
|||||||
|
|
||||||
// a valid constant name starts with a letter or underscore,
|
// a valid constant name starts with a letter or underscore,
|
||||||
// followed by any number of letters, numbers, or underscores.
|
// followed by any number of letters, numbers, or underscores.
|
||||||
define("FOO", "something");
|
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 choosen name without a $
|
||||||
echo FOO; // Returns 'something'
|
echo FOO; // Returns 'something'
|
||||||
echo 'This outputs '.FOO; // Returns 'This ouputs something'
|
echo 'This outputs ' . FOO; // Returns 'This ouputs something'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -765,6 +767,37 @@ I'm a ParentClass
|
|||||||
But I'm ChildClass
|
But I'm ChildClass
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* Magic constants
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Get current class name. Must be used inside a class declaration.
|
||||||
|
echo "Current class name is " . __CLASS__;
|
||||||
|
|
||||||
|
// Get full path directory of a file
|
||||||
|
echo "Current directory is " . __DIR__;
|
||||||
|
|
||||||
|
// Typical usage
|
||||||
|
require __DIR__ . '/vendor/autoload.php';
|
||||||
|
|
||||||
|
// Get full path of a file
|
||||||
|
echo "Current file path is " . __FILE__;
|
||||||
|
|
||||||
|
// Get current function name
|
||||||
|
echo "Current function name is " . __FUNCTION__;
|
||||||
|
|
||||||
|
// Get current line number
|
||||||
|
echo "Current line number is " . __LINE__;
|
||||||
|
|
||||||
|
// Get the name of the current method. Only returns a value when used inside a trait or object declaration.
|
||||||
|
echo "Current method is " . __METHOD__;
|
||||||
|
|
||||||
|
// Get the name of the current namespace
|
||||||
|
echo "Current namespace is " . __NAMESPACE__;
|
||||||
|
|
||||||
|
// Get the name of the current trait. Only returns a value when used inside a trait or object declaration.
|
||||||
|
echo "Current namespace is " . __TRAIT__;
|
||||||
|
|
||||||
/**********************
|
/**********************
|
||||||
* Error Handling
|
* Error Handling
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
@ -163,7 +163,7 @@ z repozytorium CPAN do zrealizowania konkretnego zadania.
|
|||||||
|
|
||||||
#### Do doczytania
|
#### Do doczytania
|
||||||
|
|
||||||
- [perl-tutorial](http://perl-tutorial.org/)
|
- [perl-tutorial](http://perl-tutorial.org/)
|
||||||
- [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html)
|
- [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html)
|
||||||
- [perldoc](http://perldoc.perl.org/)
|
- [perldoc](http://perldoc.perl.org/)
|
||||||
- wbudowane w Perla: `perldoc perlintro`
|
- wbudowane w Perla: `perldoc perlintro`
|
||||||
|
@ -30,7 +30,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
|
|||||||
# Pojedyncze komentarze oznaczamy takim symbolem.
|
# Pojedyncze komentarze oznaczamy takim symbolem.
|
||||||
|
|
||||||
""" Wielolinijkowe napisy zapisywane są przy użyciu
|
""" Wielolinijkowe napisy zapisywane są przy użyciu
|
||||||
trzech znaków cudzysłowiu i często
|
potrójnych cudzysłowów i często
|
||||||
wykorzystywane są jako komentarze.
|
wykorzystywane są jako komentarze.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@ -47,11 +47,11 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
|
|||||||
10 * 2 # => 20
|
10 * 2 # => 20
|
||||||
35 / 5 # => 7
|
35 / 5 # => 7
|
||||||
|
|
||||||
# Dzielenie może być kłopotliwe. Poniższe to dzielenie
|
# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie
|
||||||
# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany.
|
# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany.
|
||||||
5 / 2 # => 2
|
5 / 2 # => 2
|
||||||
|
|
||||||
# Aby to naprawić musimy powiedzieć nieco o liczbach zmiennoprzecinkowych.
|
# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych.
|
||||||
2.0 # To liczba zmiennoprzecinkowa, tzw. float
|
2.0 # To liczba zmiennoprzecinkowa, tzw. float
|
||||||
11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej
|
11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
|
|||||||
# Operator modulo - wyznaczanie reszty z dzielenia
|
# Operator modulo - wyznaczanie reszty z dzielenia
|
||||||
7 % 3 # => 1
|
7 % 3 # => 1
|
||||||
|
|
||||||
# Potęgowanie (x do potęgi ytej)
|
# Potęgowanie (x do potęgi y-tej)
|
||||||
2**4 # => 16
|
2**4 # => 16
|
||||||
|
|
||||||
# Wymuszanie pierwszeństwa w nawiasach
|
# Wymuszanie pierwszeństwa w nawiasach
|
||||||
@ -83,7 +83,7 @@ False or True #=> True # Prawda
|
|||||||
2 == True #=> False
|
2 == True #=> False
|
||||||
k1 == True #=> True
|
k1 == True #=> True
|
||||||
|
|
||||||
# aby zanegować użyj "not"
|
# aby zanegować, użyj "not"
|
||||||
not True # => False
|
not True # => False
|
||||||
not False # => True
|
not False # => True
|
||||||
|
|
||||||
@ -112,7 +112,7 @@ not False # => True
|
|||||||
# Napisy można dodawać!
|
# Napisy można dodawać!
|
||||||
"Witaj " + "świecie!" # => "Witaj świecie!"
|
"Witaj " + "świecie!" # => "Witaj świecie!"
|
||||||
|
|
||||||
# ... a nawet mnożone
|
# ... a nawet mnożyć
|
||||||
"Hej" * 3 # => "HejHejHej"
|
"Hej" * 3 # => "HejHejHej"
|
||||||
|
|
||||||
# Napis może być traktowany jako lista znaków
|
# Napis może być traktowany jako lista znaków
|
||||||
@ -124,7 +124,7 @@ not False # => True
|
|||||||
# Jednak nowszym sposobem formatowania jest metoda "format".
|
# Jednak nowszym sposobem formatowania jest metoda "format".
|
||||||
# Ta metoda jest obecnie polecana:
|
# Ta metoda jest obecnie polecana:
|
||||||
"{0} są {1}".format("napisy", "fajne")
|
"{0} są {1}".format("napisy", "fajne")
|
||||||
# Jeśli nie chce ci się liczyć użyj słów kluczowych.
|
# Jeśli nie chce ci się liczyć, użyj słów kluczowych.
|
||||||
"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron")
|
"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron")
|
||||||
|
|
||||||
# None jest obiektem
|
# None jest obiektem
|
||||||
@ -135,12 +135,12 @@ None # => None
|
|||||||
"etc" is None # => False
|
"etc" is None # => False
|
||||||
None is None # => True
|
None is None # => True
|
||||||
|
|
||||||
# Operator 'is' testuje identyczność obiektów. To nie jest zbyt
|
# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt
|
||||||
# pożyteczne, gdy działamy tylko na prostych wartościach,
|
# pożyteczne, gdy działamy tylko na prostych wartościach,
|
||||||
# ale przydaje się, gdy mamy do czynienia z obiektami.
|
# ale przydaje się, gdy mamy do czynienia z obiektami.
|
||||||
|
|
||||||
# None, 0, i pusty napis "" są odpowiednikami logicznego False.
|
# None, 0 i pusty napis "" są odpowiednikami logicznego False.
|
||||||
# Wszystkie inne wartości są True
|
# Wszystkie inne wartości są uznawane za prawdę (True)
|
||||||
bool(0) # => False
|
bool(0) # => False
|
||||||
bool("") # => False
|
bool("") # => False
|
||||||
|
|
||||||
@ -149,20 +149,20 @@ bool("") # => False
|
|||||||
## 2. Zmienne i zbiory danych
|
## 2. Zmienne i zbiory danych
|
||||||
####################################################
|
####################################################
|
||||||
|
|
||||||
# Python ma wyrażenie wypisujące "print" we wszystkich wersjach 2.x, ale
|
# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale
|
||||||
# zostało usunięte z wersji 3.
|
# została ona usunięta z wersji 3.
|
||||||
print "Jestem Python. Miło poznać!"
|
print "Jestem Python. Miło Cię poznać!"
|
||||||
# Python ma też funkcję "print" dostępną w wersjach 2.7 and 3...
|
# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3...
|
||||||
# ale w 2.7 musisz dodać import (odkomentuj):
|
# ale w 2.7 musisz dodać import (odkomentuj):
|
||||||
# from __future__ import print_function
|
# from __future__ import print_function
|
||||||
print("Ja też jestem Python! ")
|
print("Ja też jestem Python! ")
|
||||||
|
|
||||||
# Nie trzeba deklarować zmiennych przed przypisaniem.
|
# Nie trzeba deklarować zmiennych przed przypisaniem.
|
||||||
jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i kładki _
|
jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _
|
||||||
jakas_zmienna # => 5
|
jakas_zmienna # => 5
|
||||||
|
|
||||||
# Próba dostępu do niezadeklarowanej zmiennej da błąd.
|
# Próba dostępu do niezadeklarowanej zmiennej da błąd.
|
||||||
# Przejdź do sekcji Obsługa wyjątków po więcej...
|
# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej...
|
||||||
inna_zmienna # Wyrzuca nazwę błędu
|
inna_zmienna # Wyrzuca nazwę błędu
|
||||||
|
|
||||||
# "if" może być użyte jako wyrażenie
|
# "if" może być użyte jako wyrażenie
|
||||||
@ -173,7 +173,7 @@ li = []
|
|||||||
# Możesz zacząć od wypełnionej listy
|
# Możesz zacząć od wypełnionej listy
|
||||||
inna_li = [4, 5, 6]
|
inna_li = [4, 5, 6]
|
||||||
|
|
||||||
# Dodaj na koniec używając "append"
|
# Dodaj na koniec, używając "append"
|
||||||
li.append(1) # li to teraz [1]
|
li.append(1) # li to teraz [1]
|
||||||
li.append(2) # li to teraz [1, 2]
|
li.append(2) # li to teraz [1, 2]
|
||||||
li.append(4) # li to teraz [1, 2, 4]
|
li.append(4) # li to teraz [1, 2, 4]
|
||||||
@ -185,7 +185,7 @@ li.append(3) # li to znowu [1, 2, 4, 3].
|
|||||||
|
|
||||||
# Dostęp do list jak do każdej tablicy
|
# Dostęp do list jak do każdej tablicy
|
||||||
li[0] # => 1
|
li[0] # => 1
|
||||||
# Użyj = aby nadpisać wcześniej wypełnione miejsca w liście
|
# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku =
|
||||||
li[0] = 42
|
li[0] = 42
|
||||||
li[0] # => 42
|
li[0] # => 42
|
||||||
li[0] = 1 # Uwaga: ustawiamy starą wartość
|
li[0] = 1 # Uwaga: ustawiamy starą wartość
|
||||||
@ -195,7 +195,7 @@ li[-1] # => 3
|
|||||||
# Jeżeli wyjdziesz poza zakres...
|
# Jeżeli wyjdziesz poza zakres...
|
||||||
li[4] # ... zobaczysz IndexError
|
li[4] # ... zobaczysz IndexError
|
||||||
|
|
||||||
# Możesz tworzyć wyniki.
|
# Możesz też tworzyć wycinki.
|
||||||
li[1:3] # => [2, 4]
|
li[1:3] # => [2, 4]
|
||||||
# Bez początku
|
# Bez początku
|
||||||
li[2:] # => [4, 3]
|
li[2:] # => [4, 3]
|
||||||
@ -213,12 +213,12 @@ del li[2] # li to teraz [1, 2, 3]
|
|||||||
|
|
||||||
# Listy można dodawać
|
# Listy można dodawać
|
||||||
li + inna_li # => [1, 2, 3, 4, 5, 6]
|
li + inna_li # => [1, 2, 3, 4, 5, 6]
|
||||||
# Uwaga: wartości poszczególnych list się nie zmieniają.
|
# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają.
|
||||||
|
|
||||||
# Do łączenia list użyj "extend()"
|
# Do łączenia list użyj "extend()"
|
||||||
li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6]
|
li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6]
|
||||||
|
|
||||||
# Sprawdź czy jest w liście używając "in"
|
# Sprawdź, czy element jest w liście używając "in"
|
||||||
1 in li # => True
|
1 in li # => True
|
||||||
|
|
||||||
# "len()" pokazuje długość listy
|
# "len()" pokazuje długość listy
|
||||||
@ -238,7 +238,7 @@ tup[:2] # => (1, 2)
|
|||||||
|
|
||||||
# Można rozpakować krotki i listy do poszczególych zmiennych
|
# Można rozpakować krotki i listy do poszczególych zmiennych
|
||||||
a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3
|
a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3
|
||||||
# Jeżeli zapomnisz nawiasów automatycznie tworzone są krotki
|
# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki
|
||||||
d, e, f = 4, 5, 6
|
d, e, f = 4, 5, 6
|
||||||
# Popatrz jak prosto zamienić wartości
|
# Popatrz jak prosto zamienić wartości
|
||||||
e, d = d, e # d to teraz 5 a e to 4
|
e, d = d, e # d to teraz 5 a e to 4
|
||||||
@ -252,28 +252,28 @@ pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3}
|
|||||||
# Podglądany wartość
|
# Podglądany wartość
|
||||||
pelen_slownik["one"] # => 1
|
pelen_slownik["one"] # => 1
|
||||||
|
|
||||||
# Wypisz wszystkie klucze używając "keys()"
|
# Wypisz wszystkie klucze, używając "keys()"
|
||||||
pelen_slownik.keys() # => ["trzy", "dwa", "raz"]
|
pelen_slownik.keys() # => ["trzy", "dwa", "raz"]
|
||||||
# Uwaga: słowniki nie gwarantują kolejności występowania kluczy.
|
# Uwaga: słowniki nie zapamiętują kolejności kluczy.
|
||||||
|
|
||||||
# A teraz wszystkie wartości "values()"
|
# A teraz wszystkie wartości "values()"
|
||||||
pelen_slownik.values() # => [3, 2, 1]
|
pelen_slownik.values() # => [3, 2, 1]
|
||||||
# Uwaga: to samo dotyczy wartości.
|
# Uwaga: to samo dotyczy wartości.
|
||||||
|
|
||||||
# Sprawdzanie czy występuje to "in"
|
# Sprawdzanie czy klucz występuje w słowniku za pomocą "in"
|
||||||
"raz" in pelen_slownik # => True
|
"raz" in pelen_slownik # => True
|
||||||
1 in pelen_slownik # => False
|
1 in pelen_slownik # => False
|
||||||
|
|
||||||
# Próba dobrania się do nieistniejącego klucza da KeyError
|
# Próba dobrania się do nieistniejącego klucza da KeyError
|
||||||
pelen_slownik["cztery"] # KeyError
|
pelen_slownik["cztery"] # KeyError
|
||||||
|
|
||||||
# Użyj "get()" method aby uniknąć KeyError
|
# Użyj metody "get()", aby uniknąć błędu KeyError
|
||||||
pelen_slownik.get("raz") # => 1
|
pelen_slownik.get("raz") # => 1
|
||||||
pelen_slownik.get("cztery") # => None
|
pelen_slownik.get("cztery") # => None
|
||||||
# Metoda get zwraca domyślną wartość gdy brakuje klucza
|
# Metoda get zwraca domyślną wartość gdy brakuje klucza
|
||||||
pelen_slownik.get("one", 4) # => 1
|
pelen_slownik.get("one", 4) # => 1
|
||||||
pelen_slownik.get("cztery", 4) # => 4
|
pelen_slownik.get("cztery", 4) # => 4
|
||||||
# zauważ, że pelen_slownik.get("cztery") jest wciąż => None
|
# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None
|
||||||
# (get nie ustawia wartości słownika)
|
# (get nie ustawia wartości słownika)
|
||||||
|
|
||||||
# przypisz wartość do klucza podobnie jak w listach
|
# przypisz wartość do klucza podobnie jak w listach
|
||||||
@ -284,12 +284,12 @@ pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5
|
|||||||
pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5
|
pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5
|
||||||
|
|
||||||
|
|
||||||
# Teraz zbiory (set) ... cóż zbiory (to po prostu listy ale bez potórzeń)
|
# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń
|
||||||
pusty_zbior = set()
|
pusty_zbior = set()
|
||||||
# Inicjalizujemy "set()" pewnymi wartościami
|
# Inicjalizujemy "set()" pewnymi wartościami
|
||||||
jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4])
|
jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4])
|
||||||
|
|
||||||
# kolejność nie jest gwarantowana, nawet gdy wydaje się posortowane
|
# kolejność nie jest zachowana, nawet gdy wydaje się posortowane
|
||||||
inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4])
|
inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4])
|
||||||
|
|
||||||
# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru
|
# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru
|
||||||
@ -298,7 +298,7 @@ pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
|
|||||||
# Dodaj więcej elementów przez "add()"
|
# Dodaj więcej elementów przez "add()"
|
||||||
pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5}
|
pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5}
|
||||||
|
|
||||||
# Znajdź przecięcie zbiorów używając &
|
# Znajdź przecięcie (część wspólną) zbiorów, używając &
|
||||||
inny_zbior = {3, 4, 5, 6}
|
inny_zbior = {3, 4, 5, 6}
|
||||||
pelen_zbior & other_set # => {3, 4, 5}
|
pelen_zbior & other_set # => {3, 4, 5}
|
||||||
|
|
||||||
@ -317,32 +317,32 @@ pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6}
|
|||||||
## 3. Kontrola przepływu
|
## 3. Kontrola przepływu
|
||||||
####################################################
|
####################################################
|
||||||
|
|
||||||
# Tworzymy zmienną some_var
|
# Tworzymy zmienną jakas_zm
|
||||||
some_var = 5
|
jakas_zm = 5
|
||||||
|
|
||||||
# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie!
|
# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne!
|
||||||
# wypisze "some_var jest mniejsza niż 10"
|
# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10"
|
||||||
if some_var > 10:
|
if jakas_zm > 10:
|
||||||
print("some_var jest wieksza niż 10")
|
print("jakas_zm jest wieksza niż 10")
|
||||||
elif some_var < 10: # This elif clause is optional.
|
elif some_var < 10: # Opcjonalna klauzula elif
|
||||||
print("some_var jest mniejsza niż 10")
|
print("jakas_zm jest mniejsza niż 10")
|
||||||
else: # This is optional too.
|
else: # Również opcjonalna klauzula else
|
||||||
print("some_var jest równa 10")
|
print("jakas_zm jest równa 10")
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Pętla for iteruje po elementach listy wypisując:
|
Pętla for iteruje po elementach listy, wypisując:
|
||||||
pies to ssak
|
pies to ssak
|
||||||
kot to ssak
|
kot to ssak
|
||||||
mysz to ssak
|
mysz to ssak
|
||||||
"""
|
"""
|
||||||
for zwierze in ["pies", "kot", "mysz"]:
|
for zwierze in ["pies", "kot", "mysz"]:
|
||||||
# Możesz użyć % aby stworzyć sformatowane napisy
|
# Użyj metody format, aby umieścić wartość zmiennej w ciągu
|
||||||
print("%s to ssak" % zwierze)
|
print("{0} to ssak".format(zwierze))
|
||||||
|
|
||||||
"""
|
"""
|
||||||
"range(liczba)" zwraca listę liczb
|
"range(liczba)" zwraca listę liczb
|
||||||
od zera do danej liczby:
|
z przedziału od zera do wskazanej liczby (bez niej):
|
||||||
0
|
0
|
||||||
1
|
1
|
||||||
2
|
2
|
||||||
@ -352,7 +352,7 @@ for i in range(4):
|
|||||||
print(i)
|
print(i)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
While to pętla która jest wykonywana dopóki spełniony jest warunek:
|
While to pętla, która jest wykonywana, dopóki spełniony jest warunek:
|
||||||
0
|
0
|
||||||
1
|
1
|
||||||
2
|
2
|
||||||
@ -363,46 +363,46 @@ while x < 4:
|
|||||||
print(x)
|
print(x)
|
||||||
x += 1 # Skrót od x = x + 1
|
x += 1 # Skrót od x = x + 1
|
||||||
|
|
||||||
# Wyjątki wyłapujemy używając try, except
|
# Wyjątki wyłapujemy, używając try i except
|
||||||
|
|
||||||
# Działa w Pythonie 2.6 i wyższych:
|
# Działa w Pythonie 2.6 i wyższych:
|
||||||
try:
|
try:
|
||||||
# Użyj "raise" aby wyrzucić wyjąte
|
# Użyj "raise" aby wyrzucić wyjątek
|
||||||
raise IndexError("To błąd indeksu")
|
raise IndexError("To błąd indeksu")
|
||||||
except IndexError as e:
|
except IndexError as e:
|
||||||
pass # Pass to brak reakcji na błąd. Zazwyczaj nanosisz tu poprawki.
|
pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu.
|
||||||
except (TypeError, NameError):
|
except (TypeError, NameError):
|
||||||
pass # kilka wyjątków może być przechwyce razem.
|
pass # kilka wyjątków można przechwycić jednocześnie.
|
||||||
else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu
|
else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu
|
||||||
print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku.
|
print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku.
|
||||||
|
|
||||||
|
|
||||||
####################################################
|
####################################################
|
||||||
## 4. Funkcjie
|
## 4. Funkcje
|
||||||
####################################################
|
####################################################
|
||||||
|
|
||||||
# Użyj "def" aby stworzyć nową funkcję
|
# Użyj "def", aby stworzyć nową funkcję
|
||||||
def dodaj(x, y):
|
def dodaj(x, y):
|
||||||
print("x to %s a y to %s" % (x, y))
|
print("x to %s, a y to %s" % (x, y))
|
||||||
return x + y # słówko kluczowe return zwraca wynik działania
|
return x + y # słowo kluczowe return zwraca wynik działania
|
||||||
|
|
||||||
# Tak wywołuje się funkcję z parametrami (args):
|
# Tak wywołuje się funkcję z parametrami:
|
||||||
dodaj(5, 6) # => wypisze "x to 5 a y to 6" i zwróci 11
|
dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11
|
||||||
|
|
||||||
# Innym sposobem jest wywołanie z parametrami nazwanymi.
|
# Innym sposobem jest wywołanie z parametrami nazwanymi.
|
||||||
dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia.
|
dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia.
|
||||||
|
|
||||||
|
|
||||||
# Można też stworzyć funkcję, które przyjmują różną ilość parametrów
|
# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych,
|
||||||
# nienazwanych args, co będzie interpretowane jako krotka jeśli nie użyjesz *
|
# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args"
|
||||||
def varargs(*args):
|
def varargs(*args):
|
||||||
return args
|
return args
|
||||||
|
|
||||||
varargs(1, 2, 3) # => (1, 2, 3)
|
varargs(1, 2, 3) # => (1, 2, 3)
|
||||||
|
|
||||||
|
|
||||||
# Można też stworzyć funkcję, które przyjmują różną ilość parametrów
|
# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów
|
||||||
# nazwanych kwargs, które będa interpretowane jako słownik jeśli nie dasz **
|
# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs"
|
||||||
def keyword_args(**kwargs):
|
def keyword_args(**kwargs):
|
||||||
return kwargs
|
return kwargs
|
||||||
|
|
||||||
@ -410,12 +410,12 @@ def keyword_args(**kwargs):
|
|||||||
keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"}
|
keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"}
|
||||||
|
|
||||||
|
|
||||||
# Możesz też to pomieszać
|
# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych
|
||||||
def all_the_args(*args, **kwargs):
|
def all_the_args(*args, **kwargs):
|
||||||
print(args)
|
print(args)
|
||||||
print(kwargs)
|
print(kwargs)
|
||||||
"""
|
"""
|
||||||
all_the_args(1, 2, a=3, b=4) wyrzuci:
|
all_the_args(1, 2, a=3, b=4) wypisze:
|
||||||
(1, 2)
|
(1, 2)
|
||||||
{"a": 3, "b": 4}
|
{"a": 3, "b": 4}
|
||||||
"""
|
"""
|
||||||
@ -435,7 +435,7 @@ def pass_all_the_args(*args, **kwargs):
|
|||||||
print varargs(*args)
|
print varargs(*args)
|
||||||
print keyword_args(**kwargs)
|
print keyword_args(**kwargs)
|
||||||
|
|
||||||
# Zakres widoczności
|
# Zasięg zmiennych
|
||||||
x = 5
|
x = 5
|
||||||
|
|
||||||
def setX(num):
|
def setX(num):
|
||||||
@ -461,14 +461,14 @@ def rob_dodawacz(x):
|
|||||||
dodaj_10 = rob_dodawacz(10)
|
dodaj_10 = rob_dodawacz(10)
|
||||||
dodaj_10(3) # => 13
|
dodaj_10(3) # => 13
|
||||||
|
|
||||||
# Są również funkcje nienazwane "lambda"
|
# Są również funkcje anonimowe "lambda"
|
||||||
(lambda x: x > 2)(3) # => True
|
(lambda x: x > 2)(3) # => True
|
||||||
|
|
||||||
# Są także wbudowane funkcje wysokiego poziomu
|
# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr)
|
||||||
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
||||||
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||||
|
|
||||||
# Można używać wyrażeń listowych do mapowania (map) i filtrowania (filter)
|
# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania
|
||||||
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
|
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
|
||||||
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
|
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
|
||||||
|
|
||||||
@ -485,18 +485,18 @@ class Czlowiek(object):
|
|||||||
|
|
||||||
# Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji.
|
# Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji.
|
||||||
# Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają
|
# Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają
|
||||||
# obietky lub atrybuty, który żyją tylko w kontrolowanej przez
|
# specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona.
|
||||||
# użytkownika przestrzeni nazw. Nie używaj ich we własnych metodach.
|
# Nie używaj ich we własnych metodach.
|
||||||
def __init__(self, nazwa):
|
def __init__(self, nazwa):
|
||||||
# przypisz parametr "nazwa" do atrybutu instancji
|
# przypisz parametr "nazwa" do atrybutu instancji
|
||||||
self.nazwa = nazwa
|
self.nazwa = nazwa
|
||||||
|
|
||||||
# Metoda instancji. Wszystkie metody biorą "self" jako pierwszy argument
|
# Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument
|
||||||
def mow(self, wiadomosc):
|
def mow(self, wiadomosc):
|
||||||
return "%s: %s" % (self.nazwa, wiadomosc)
|
return "%s: %s" % (self.nazwa, wiadomosc)
|
||||||
|
|
||||||
# Metoda klasowa współdzielona przez instancje.
|
# Metoda klasowa współdzielona przez instancje.
|
||||||
# Ma wywołującą klasę jako pierwszy argument.
|
# Przyjmuje wywołującą klasę jako pierwszy argument.
|
||||||
@classmethod
|
@classmethod
|
||||||
def daj_gatunek(cls):
|
def daj_gatunek(cls):
|
||||||
return cls.gatunek
|
return cls.gatunek
|
||||||
@ -540,7 +540,8 @@ print(ceil(3.7)) # => 4.0
|
|||||||
print(floor(3.7)) # => 3.0
|
print(floor(3.7)) # => 3.0
|
||||||
|
|
||||||
# Można zaimportować wszystkie funkcje z danego modułu.
|
# Można zaimportować wszystkie funkcje z danego modułu.
|
||||||
# Ostrzeżenie: nie jest to polecane.
|
# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się,
|
||||||
|
# która funkcja pochodzi z którego modułu.
|
||||||
from math import *
|
from math import *
|
||||||
|
|
||||||
# Można skracać nazwy modułów.
|
# Można skracać nazwy modułów.
|
||||||
@ -550,7 +551,7 @@ math.sqrt(16) == m.sqrt(16) # => True
|
|||||||
from math import sqrt
|
from math import sqrt
|
||||||
math.sqrt == m.sqrt == sqrt # => True
|
math.sqrt == m.sqrt == sqrt # => True
|
||||||
|
|
||||||
# Moduły pythona to zwykłe skrypty napisane w tym języku. Możesz
|
# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz
|
||||||
# pisać własne i importować je. Nazwa modułu to nazwa pliku.
|
# pisać własne i importować je. Nazwa modułu to nazwa pliku.
|
||||||
|
|
||||||
# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu.
|
# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu.
|
||||||
@ -568,14 +569,16 @@ def podwojne_liczby(iterowalne):
|
|||||||
yield i + i
|
yield i + i
|
||||||
|
|
||||||
# Generatory tworzą wartości w locie.
|
# Generatory tworzą wartości w locie.
|
||||||
# W przeciwienstwie do wygenerowania wartości raz i ich zachowania,
|
# Zamiast generować wartości raz i zapisywać je (np. w liście),
|
||||||
# powstają one na bieżąco, w wyniku iteracji. To oznacza, że wartości
|
# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza,
|
||||||
# większe niż 15 nie będą przetworzone w funkcji "podwojne_liczby".
|
# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone
|
||||||
|
# w funkcji "podwojne_liczby".
|
||||||
# Zauważ, że xrange to generator, który wykonuje tę samą operację co range.
|
# Zauważ, że xrange to generator, który wykonuje tę samą operację co range.
|
||||||
# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci,
|
# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci,
|
||||||
# a xrange tworzy obiekt generatora zamiast tworzyć całą listę jak range.
|
# a xrange tworzy obiekt generatora zamiast budować całą listę jak range.
|
||||||
# Użyto podkreślinika, aby odróżnić nazwę zmiennej od słówka kluczowego
|
|
||||||
# Pythona.
|
# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy
|
||||||
|
# zwykle na końcu znaku podkreślenia
|
||||||
xrange_ = xrange(1, 900000000)
|
xrange_ = xrange(1, 900000000)
|
||||||
|
|
||||||
# poniższa pętla będzie podwajać liczby aż do 30
|
# poniższa pętla będzie podwajać liczby aż do 30
|
||||||
@ -587,7 +590,7 @@ for i in podwojne_liczby(xrange_):
|
|||||||
|
|
||||||
# Dekoratory
|
# Dekoratory
|
||||||
# w tym przykładzie "beg" jest nakładką na "say"
|
# w tym przykładzie "beg" jest nakładką na "say"
|
||||||
# Beg wywołuje say. Jeśli say_please jest prawdziwe wtedy wzracana wartość
|
# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość
|
||||||
# zostanie zmieniona
|
# zostanie zmieniona
|
||||||
|
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
593
pl-pl/ruby-pl.html.markdown
Normal file
593
pl-pl/ruby-pl.html.markdown
Normal file
@ -0,0 +1,593 @@
|
|||||||
|
---
|
||||||
|
language: ruby
|
||||||
|
filename: learnruby.rb
|
||||||
|
contributors:
|
||||||
|
- ["David Underwood", "http://theflyingdeveloper.com"]
|
||||||
|
- ["Joel Walden", "http://joelwalden.net"]
|
||||||
|
- ["Luke Holder", "http://twitter.com/lukeholder"]
|
||||||
|
- ["Tristan Hume", "http://thume.ca/"]
|
||||||
|
- ["Nick LaMuro", "https://github.com/NickLaMuro"]
|
||||||
|
- ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
|
||||||
|
- ["Ariel Krakowski", "http://www.learneroo.com"]
|
||||||
|
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
|
||||||
|
- ["Levi Bostian", "https://github.com/levibostian"]
|
||||||
|
- ["Rahil Momin", "https://github.com/iamrahil"]
|
||||||
|
- ["Gabriel Halley", "https://github.com/ghalley"]
|
||||||
|
- ["Persa Zula", "http://persazula.com"]
|
||||||
|
translators:
|
||||||
|
- ["Marcin Klocek", "https://github.com/mklocek"]
|
||||||
|
lang: pl-pl
|
||||||
|
---
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
# To jest komentarz
|
||||||
|
|
||||||
|
=begin
|
||||||
|
To jest wielolinijkowy komentarz
|
||||||
|
Nikt ich nie używa
|
||||||
|
Ty też nie powinieneś
|
||||||
|
=end
|
||||||
|
|
||||||
|
# Przede wszystkim: Wszystko jest obiektem.
|
||||||
|
|
||||||
|
# Liczby są obiektami
|
||||||
|
|
||||||
|
3.class #=> Fixnum
|
||||||
|
|
||||||
|
3.to_s #=> "3"
|
||||||
|
|
||||||
|
|
||||||
|
# Trochę podstawowej arytmetyki
|
||||||
|
1 + 1 #=> 2
|
||||||
|
8 - 1 #=> 7
|
||||||
|
10 * 2 #=> 20
|
||||||
|
35 / 5 #=> 7
|
||||||
|
2**5 #=> 32
|
||||||
|
5 % 3 #=> 2
|
||||||
|
5 ^ 6 #=> 3
|
||||||
|
|
||||||
|
# Arytmetyka jest zastąpeniem składni
|
||||||
|
# metod wywoływanych na obiektach
|
||||||
|
1.+(3) #=> 4
|
||||||
|
10.* 5 #=> 50
|
||||||
|
|
||||||
|
# Wartości specjalne są obiektami
|
||||||
|
nil # To na prawdę jest niczym
|
||||||
|
true # prawda
|
||||||
|
false # fałsz
|
||||||
|
|
||||||
|
nil.class #=> NilClass
|
||||||
|
true.class #=> TrueClass
|
||||||
|
false.class #=> FalseClass
|
||||||
|
|
||||||
|
# Równość
|
||||||
|
1 == 1 #=> true
|
||||||
|
2 == 1 #=> false
|
||||||
|
|
||||||
|
# Nierówność
|
||||||
|
1 != 1 #=> false
|
||||||
|
2 != 1 #=> true
|
||||||
|
|
||||||
|
# jedyną 'fałszywą' wartością poza false, jest nil
|
||||||
|
|
||||||
|
!nil #=> true
|
||||||
|
!false #=> true
|
||||||
|
!0 #=> false
|
||||||
|
|
||||||
|
# Więcej porównań
|
||||||
|
1 < 10 #=> true
|
||||||
|
1 > 10 #=> false
|
||||||
|
2 <= 2 #=> true
|
||||||
|
2 >= 2 #=> true
|
||||||
|
|
||||||
|
# Operatory logiczne
|
||||||
|
true && false #=> false
|
||||||
|
true || false #=> true
|
||||||
|
!true #=> false
|
||||||
|
|
||||||
|
# Istnieją alternatywne wersje operatorów logicznych ze znacznie mniejszym
|
||||||
|
# pierwszeństwem. Używane są by kontrolować wyrażenia w łańcuchach wyrażeń
|
||||||
|
# aż jedno z nich wróci true lub false.
|
||||||
|
|
||||||
|
# `zrob_cos_innego` wywołaj tylko wtedy gdy `zrob_cos` zakończy się sukcesem.
|
||||||
|
zrob_cos_innego() and zrob_cos()
|
||||||
|
# `log_error` wywołaj tylko wtedy gdy `zrob_cos` nie zakończy się sukcesem.
|
||||||
|
zrob_cos() or log_error()
|
||||||
|
|
||||||
|
|
||||||
|
# Stringi są obiektami
|
||||||
|
|
||||||
|
'Jestem stringiem.'.class #=> String
|
||||||
|
"Ja również jestem stringiem.".class #=> String
|
||||||
|
|
||||||
|
wypelnienie = 'użyć interpolacji stringa'
|
||||||
|
"Potrafię #{wypelnienie} używając podwójnych cudzysłowów."
|
||||||
|
#=> "Potrafię użyć interpolacji stringa używając podwójnych cudzysłowów."
|
||||||
|
|
||||||
|
# Staraj się zapisywać stringi za pomocą apostrof, zamiast cudzysłowów tam, gdzie to możliwe
|
||||||
|
# Cudzysłowy wykonują dodatkowe wewnętrzne operacje
|
||||||
|
|
||||||
|
|
||||||
|
# Łączenie stringów, ale nie liczb
|
||||||
|
'hej ' + 'świecie' #=> "hej świecie"
|
||||||
|
'hej ' + 3 #=> TypeError: can't convert Fixnum into String
|
||||||
|
'hej ' + 3.to_s #=> "hej 3"
|
||||||
|
|
||||||
|
# Łączenie stringów i operatorów
|
||||||
|
'hej ' * 3 #=> "hej hej hej "
|
||||||
|
|
||||||
|
# Dodawanie do stringa
|
||||||
|
'hej' << ' świecie' #=> "hej świecie"
|
||||||
|
|
||||||
|
# wydrukowanie wartości wraz z nową linią na końcu
|
||||||
|
puts "Drukuję!"
|
||||||
|
#=> Drukuję!
|
||||||
|
#=> nil
|
||||||
|
|
||||||
|
# wydrukowanie wartości bez nowej linii na końcu
|
||||||
|
print "Drukuję!"
|
||||||
|
#=> Drukuję! => nill
|
||||||
|
|
||||||
|
# Zmienne
|
||||||
|
x = 25 #=> 25
|
||||||
|
x #=> 25
|
||||||
|
|
||||||
|
# Zauważ, że przypisanie zwraca przypisywaną wartość
|
||||||
|
# To znaczy, że możesz wykonać wielokrotne przypisanie:
|
||||||
|
|
||||||
|
x = y = 10 #=> 10
|
||||||
|
x #=> 10
|
||||||
|
y #=> 10
|
||||||
|
|
||||||
|
# Zwyczajowo, używaj notacji nazwa_zmiennej dla nazw zmiennych
|
||||||
|
nazwa_zmiennej = true
|
||||||
|
|
||||||
|
# Używaj opisowych nazw zmiennych
|
||||||
|
sciezka_do_projektu = '/dobra/nazwa/'
|
||||||
|
sciezka = '/zla/nazwa/'
|
||||||
|
|
||||||
|
# Symbole (są obiektami)
|
||||||
|
# Symbole są niezmiennymi, wielokrotnie używanymi stałymi reprezentowanymi wewnętrznie jako
|
||||||
|
# liczby całkowite. Często używane są zamiast stringów w celu wydajniejszego przekazywania danych
|
||||||
|
|
||||||
|
:oczekujacy.class #=> Symbol
|
||||||
|
|
||||||
|
status = :oczekujacy
|
||||||
|
|
||||||
|
status == :oczekujacy #=> true
|
||||||
|
|
||||||
|
status == 'oczekujacy' #=> false
|
||||||
|
|
||||||
|
status == :zatwierdzony #=> false
|
||||||
|
|
||||||
|
# Tablice
|
||||||
|
|
||||||
|
# To jest tablica
|
||||||
|
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
|
||||||
|
|
||||||
|
# Tablice mogą zwierać różne typy danych
|
||||||
|
|
||||||
|
[1, 'hej', false] #=> [1, "hej", false]
|
||||||
|
|
||||||
|
# Tablice mogę być indeksowane
|
||||||
|
# Od początku
|
||||||
|
tablica[0] #=> 1
|
||||||
|
tablica.first #=> 1
|
||||||
|
tablica[12] #=> nil
|
||||||
|
|
||||||
|
# Podobnie jak przy arytmetyce, dostęp poprzez [zmienna]
|
||||||
|
# jest tylko czytelniejszą składnią
|
||||||
|
# dla wywoływania metody [] na obiekcie
|
||||||
|
tablica.[] 0 #=> 1
|
||||||
|
tablica.[] 12 #=> nil
|
||||||
|
|
||||||
|
# Od końca
|
||||||
|
tablica[-1] #=> 5
|
||||||
|
tablica.last #=> 5
|
||||||
|
|
||||||
|
# Z początkowym indeksem i długością
|
||||||
|
tablica[2, 3] #=> [3, 4, 5]
|
||||||
|
|
||||||
|
# Odwrotność tablicy
|
||||||
|
a=[1,2,3]
|
||||||
|
a.reverse! #=> [3,2,1]
|
||||||
|
|
||||||
|
# Lub zakres
|
||||||
|
array[1..3] #=> [2, 3, 4]
|
||||||
|
|
||||||
|
# Dodawanie do tablicy w taki sposób
|
||||||
|
tablica << 6 #=> [1, 2, 3, 4, 5, 6]
|
||||||
|
# Lub taki
|
||||||
|
tablica.push(6) #=> [1, 2, 3, 4, 5, 6]
|
||||||
|
|
||||||
|
# Sprawdzanie, czy tablica zawiera element
|
||||||
|
tablica.include?(1) #=> true
|
||||||
|
|
||||||
|
# Hasze są Ruby'owymi podstawowymi słownikami z parami klucz/wartość.
|
||||||
|
# Hasze są zapisywane za pomocą nawiasów klamrowych
|
||||||
|
hasz = { 'kolor' => 'zielony', 'numer' => 5 }
|
||||||
|
|
||||||
|
hasz.keys #=> ['kolor', 'numer']
|
||||||
|
|
||||||
|
# Można szybko sprawdzić zawartość hasza za pomocą kluczy:
|
||||||
|
hasz['kolor'] #=> 'zielony'
|
||||||
|
hasz['numer'] #=> 5
|
||||||
|
|
||||||
|
# Sprawdzenie wartośći dla nieistniejącego klucza zwraca nil:
|
||||||
|
hasz['nic tutaj nie ma'] #=> nil
|
||||||
|
|
||||||
|
# Od wersji 1.9, Ruby posiada specjalną składnię, gdy używamy symboli jako kluczy:
|
||||||
|
|
||||||
|
nowy_hasz = { stan: 3, akcja: true }
|
||||||
|
|
||||||
|
nowy_hasz.keys #=> [:stan, :akcja]
|
||||||
|
|
||||||
|
# Sprawdzenie istnienia kluczy i wartości w haszu
|
||||||
|
new_hash.has_key?(:defcon) #=> true
|
||||||
|
new_hash.has_value?(3) #=> true
|
||||||
|
|
||||||
|
# Wskazówka: Zarówno tablice, jak i hasze, są policzalne
|
||||||
|
# Współdzielą wiele metod takich jak each, map, count, i inne
|
||||||
|
|
||||||
|
# Instrukcje warunkowe
|
||||||
|
|
||||||
|
if true
|
||||||
|
'wyrażenie if'
|
||||||
|
elsif false
|
||||||
|
'wyrażenie if, opcjonalne'
|
||||||
|
else
|
||||||
|
'wyrażenie else, również opcjonalne'
|
||||||
|
end
|
||||||
|
|
||||||
|
for licznik in 1..5
|
||||||
|
puts "powtórzenie #{licznik}"
|
||||||
|
end
|
||||||
|
#=> powtórzenie 1
|
||||||
|
#=> powtórzenie 2
|
||||||
|
#=> powtórzenie 3
|
||||||
|
#=> powtórzenie 4
|
||||||
|
#=> powtórzenie 5
|
||||||
|
|
||||||
|
# JEDNAKŻE, Nikt nie używa pętli for.
|
||||||
|
# Zamiast tego, powinno się używać metody "each" i podawać jej blok.
|
||||||
|
# Blok jest kawałkiem kodu, który możesz podać metodzie podobnej do "each".
|
||||||
|
# Jest analogiczny do wyrażeń lambda, funkcji anonimowych lub zamknięć w innych
|
||||||
|
# językach programowania.
|
||||||
|
#
|
||||||
|
# Metoda "each" danego zakresu, wykonuje blok dla każdego elementu w zakresie.
|
||||||
|
# Do bloku zostaje przekazany licznik jako parametr.
|
||||||
|
# Wykonanie metody "each" z przekazaniem bloku wygląda następująco:
|
||||||
|
|
||||||
|
(1..5).each do |licznik|
|
||||||
|
puts "powtórzenie #{licznik}"
|
||||||
|
end
|
||||||
|
#=> powtórzenie 1
|
||||||
|
#=> powtórzenie 2
|
||||||
|
#=> powtórzenie 3
|
||||||
|
#=> powtórzenie 4
|
||||||
|
#=> powtórzenie 5
|
||||||
|
|
||||||
|
# Możesz również otoczyć blok nawiasami klamrowymi:
|
||||||
|
(1..5).each { |licznik| puts "powtórzenie #{licznik}" }
|
||||||
|
|
||||||
|
# Zawartość struktur danych również może być powtarzana używając each.
|
||||||
|
tablica.each do |element|
|
||||||
|
puts "#{element} jest częścią tablicy"
|
||||||
|
end
|
||||||
|
hasz.each do |klucz, wartosc|
|
||||||
|
puts "#{klucz} jest #{wartosc}"
|
||||||
|
end
|
||||||
|
|
||||||
|
# Jeśli nadal potrzebujesz indeksum, możesz użyć "each_with_index" i zdefiniować
|
||||||
|
# zmienną odpowiadającą indeksowi
|
||||||
|
tablica.each_with_index do |element, indeks|
|
||||||
|
puts "#{element} jest numerem #{indeks} w tablicy"
|
||||||
|
end
|
||||||
|
|
||||||
|
licznik = 1
|
||||||
|
while licznik <= 5 do
|
||||||
|
puts "powtórzenie #{licznik}"
|
||||||
|
licznik += 1
|
||||||
|
end
|
||||||
|
#=> powtórzenie 1
|
||||||
|
#=> powtórzenie 2
|
||||||
|
#=> powtórzenie 3
|
||||||
|
#=> powtórzenie 4
|
||||||
|
#=> powtórzenie 5
|
||||||
|
|
||||||
|
# W Ruby istnieje dużo pomocnych funkcji wykonujących pętle,
|
||||||
|
# na przykład "map", "reduce", "inject" i wiele innych. Map,
|
||||||
|
# w każdym wywołaniu, pobiera tablicę, na której wykonuję pętlę,
|
||||||
|
# wykonuje kod zapisany za pomocą bloku i zwraca całkowicie nową tablicę.
|
||||||
|
tablica = [1,2,3,4,5]
|
||||||
|
podwojone = tablica.map do |element|
|
||||||
|
element * 2
|
||||||
|
end
|
||||||
|
puts podwojona
|
||||||
|
#=> [2,4,6,8,10]
|
||||||
|
puts tablica
|
||||||
|
#=> [1,2,3,4,5]
|
||||||
|
|
||||||
|
ocena = 2
|
||||||
|
|
||||||
|
case ocena
|
||||||
|
when 1
|
||||||
|
puts 'Dobra robota, masz wolne'
|
||||||
|
when 2
|
||||||
|
puts 'Następnym razem będziesz miał więcej szczęścia'
|
||||||
|
when 3
|
||||||
|
puts 'Możesz to zrobić lepiej'
|
||||||
|
when 4
|
||||||
|
puts 'Przebrnąłeś'
|
||||||
|
when 5
|
||||||
|
puts 'Oblałeś!'
|
||||||
|
else
|
||||||
|
puts 'Inny system oceniania?'
|
||||||
|
end
|
||||||
|
#=> "Następnym razem będziesz miał więcej szczęścia"
|
||||||
|
|
||||||
|
# case może również użwać zakresów
|
||||||
|
ocena = 82
|
||||||
|
case ocena
|
||||||
|
when 90..100
|
||||||
|
puts 'Hurra!'
|
||||||
|
when 80...90
|
||||||
|
puts 'Dobra robota'
|
||||||
|
else
|
||||||
|
puts 'Oblałeś!'
|
||||||
|
end
|
||||||
|
#=> "Dobra robota"
|
||||||
|
|
||||||
|
# obsługa błędów:
|
||||||
|
begin
|
||||||
|
# kod, który może wywołać wyjątek
|
||||||
|
raise NoMemoryError, 'Zabrakło pamięci.'
|
||||||
|
rescue NoMemoryError => zmienna_wyjatku
|
||||||
|
puts 'Został wywołany NoMemoryError', zmienna_wyjatku
|
||||||
|
rescue RuntimeError => inna_zmienna_wyjatku
|
||||||
|
puts 'Teraz został wywołany RuntimeError'
|
||||||
|
else
|
||||||
|
puts 'To zostanie uruchomione, jeśli nie wystąpi żaden wyjątek'
|
||||||
|
ensure
|
||||||
|
puts 'Ten kod wykona się zawsze'
|
||||||
|
end
|
||||||
|
|
||||||
|
# Funkcje
|
||||||
|
|
||||||
|
def podwojenie(x)
|
||||||
|
x * 2
|
||||||
|
end
|
||||||
|
|
||||||
|
# Funkcje (i wszystkie bloki) zawsze zwracają wartość ostatniego wyrażenia
|
||||||
|
podwojenie(2) #=> 4
|
||||||
|
|
||||||
|
# Okrągłe nawiady są opcjonalne, gdy wynik jest jednoznaczny
|
||||||
|
podwojenie 3 #=> 6
|
||||||
|
|
||||||
|
podwojenie podwojenie 3 #=> 12
|
||||||
|
|
||||||
|
def suma(x, y)
|
||||||
|
x + y
|
||||||
|
end
|
||||||
|
|
||||||
|
# Argumenty metod są oddzielone przecinkami
|
||||||
|
suma 3, 4 #=> 7
|
||||||
|
|
||||||
|
suma suma(3, 4), 5 #=> 12
|
||||||
|
|
||||||
|
# yield
|
||||||
|
# Wszystkie metody mają ukryty, opcjonalny parametr bloku,
|
||||||
|
# który może być wykonany używając słowa kluczowego 'yield'
|
||||||
|
|
||||||
|
def otoczenie
|
||||||
|
puts '{'
|
||||||
|
yield
|
||||||
|
puts '}'
|
||||||
|
end
|
||||||
|
|
||||||
|
otoczenie { puts 'hej świecie' }
|
||||||
|
|
||||||
|
# {
|
||||||
|
# hej świecie
|
||||||
|
# }
|
||||||
|
|
||||||
|
|
||||||
|
# Możesz przekazać blok do funkcji
|
||||||
|
# "&" oznacza referencję to przekazanego bloku
|
||||||
|
def goscie(&blok)
|
||||||
|
blok.call 'jakis_argument'
|
||||||
|
end
|
||||||
|
|
||||||
|
# Możesz przekazać listę argumentów, które będę przekonwertowane na tablicę
|
||||||
|
# Do tego służy operator ("*")
|
||||||
|
def goscie(*tablica)
|
||||||
|
tablica.each { |gosc| puts gosc }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Definiowanie klas używając słowa kluczowego class
|
||||||
|
class Czlowiek
|
||||||
|
|
||||||
|
# Zmienna klasowa. Jest współdzielona przez wszystkie instancje tej klasy.
|
||||||
|
@@gatunek = 'H. sapiens'
|
||||||
|
|
||||||
|
# Podstawowe inicjalizowanie
|
||||||
|
def initialize(imie, wiek = 0)
|
||||||
|
# Przypisanie argumentu do zmiennej danej instancji o nazwie "imie"
|
||||||
|
@imie = imie
|
||||||
|
# Jeśli nie podano wieku, zostanie użyta domyślna wartość z listy argumentów.
|
||||||
|
@wiek = wiek
|
||||||
|
end
|
||||||
|
|
||||||
|
# Podstawowa metoda przypisująca wartość
|
||||||
|
def imie=(imie)
|
||||||
|
@imie = imie
|
||||||
|
end
|
||||||
|
|
||||||
|
# Podstawowa metoda pobierająca wartość
|
||||||
|
def imie
|
||||||
|
@imie
|
||||||
|
end
|
||||||
|
|
||||||
|
# Powyższa funkcjonalność może być zastąpiona używając metody attr_accessor w taki sposób
|
||||||
|
attr_accessor :imie
|
||||||
|
|
||||||
|
# Metody przypisujące/pobierające mogą być stworzone indywidualnie
|
||||||
|
attr_reader :imie
|
||||||
|
attr_writer :imie
|
||||||
|
|
||||||
|
# Metody klasowe używają self aby odróżnić się od metody instancji.
|
||||||
|
# To może być wywołane na klasie, nie na instancji.
|
||||||
|
def self.powiedz(wiadomosc)
|
||||||
|
puts wiadomosc
|
||||||
|
end
|
||||||
|
|
||||||
|
def gatunek
|
||||||
|
@@gatunek
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
|
# Tworzenie instancji klasy
|
||||||
|
jim = Czlowiek.new('Jim Halpert')
|
||||||
|
|
||||||
|
dwight = Czlowiek.new('Dwight K. Schrute')
|
||||||
|
|
||||||
|
# Wywołajmy parę metod
|
||||||
|
jim.gatunek #=> "H. sapiens"
|
||||||
|
jim.imie #=> "Jim Halpert"
|
||||||
|
jim.imie = "Jim Halpert II" #=> "Jim Halpert II"
|
||||||
|
jim.imie #=> "Jim Halpert II"
|
||||||
|
dwight.gatunek #=> "H. sapiens"
|
||||||
|
dwight.imie #=> "Dwight K. Schrute"
|
||||||
|
|
||||||
|
# Wywołanie metody klasowej
|
||||||
|
Czlowiek.powiedz('Cześć') #=> "Cześć"
|
||||||
|
|
||||||
|
# Zasięg zmiennej jest definiowany poprzez jej nazwę.
|
||||||
|
# Zmienne, które zaczynają się na $ mają zasięg globalny
|
||||||
|
$zmienna = "Jestem zmienną globalną"
|
||||||
|
defined? $zmienna #=> "global-variable"
|
||||||
|
|
||||||
|
# Zmienne zczynające się na @ mają zasięg danej instancji
|
||||||
|
@zmienna = "Jestem zmienną instancji"
|
||||||
|
defined? @zmienna #=> "instance-variable"
|
||||||
|
|
||||||
|
# Zmienne, które zaczynają się na @@ mają zasięg danej klasy
|
||||||
|
@@zmienna = "Jestem zmienną klasową"
|
||||||
|
defined? @@zmienna #=> "class variable"
|
||||||
|
|
||||||
|
# Zmienne, które zaczynają się na dużą literę, są stałymi
|
||||||
|
Zmienna = "Jestem stałą"
|
||||||
|
defined? Zmienna #=> "constant"
|
||||||
|
|
||||||
|
# Klasa jest również obiektem w ruby. Może więc mieć zmienne instancji.
|
||||||
|
# Zmienna klasowa może być współdzielona między klasą i jej potomstwem.
|
||||||
|
|
||||||
|
# podstawowa klasa
|
||||||
|
class Czlowiek
|
||||||
|
@@cokolwiek = 0
|
||||||
|
|
||||||
|
def self.cokolwiek
|
||||||
|
@@cokolwiek
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.cokolwiek=(wartosc)
|
||||||
|
@@cokolwiek = wartosc
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# klasa pochodna
|
||||||
|
class Pracownik < Czlowiek
|
||||||
|
end
|
||||||
|
|
||||||
|
Czlowiek.cokolwiek # 0
|
||||||
|
Pracownik.cokolwiek # 0
|
||||||
|
|
||||||
|
Czlowiek.cokolwiek = 2 # 2
|
||||||
|
Pracownik.cokolwiek # 2
|
||||||
|
|
||||||
|
# Zmienna instancji danej klasy nie jest współdzielona przez jej potomstwo.
|
||||||
|
|
||||||
|
class Czlowiek
|
||||||
|
@cos = 0
|
||||||
|
|
||||||
|
def self.cos
|
||||||
|
@cos
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.cos=(wartosc)
|
||||||
|
@cos = wartosc
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class Doktor < Czlowiek
|
||||||
|
end
|
||||||
|
|
||||||
|
Czlowiek.cos # 0
|
||||||
|
Doktor.cos # nil
|
||||||
|
|
||||||
|
module PrzykladowyModul
|
||||||
|
def cokolwiek
|
||||||
|
'cokolwiek'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Włączanie modułów łączy ich metody z metodami instancji klasy
|
||||||
|
# Rozszerzanie modułów łączy ich metody z metodami klasy
|
||||||
|
|
||||||
|
class Osoba
|
||||||
|
include PrzykladowyModul
|
||||||
|
end
|
||||||
|
|
||||||
|
class Ksiazka
|
||||||
|
extend PrzykladowyModul
|
||||||
|
end
|
||||||
|
|
||||||
|
Osoba.cokolwiek # => NoMethodError: undefined method `cokolwiek' for Osoba:Class
|
||||||
|
Osoba.new.cokolwiek # => 'cokolwiek'
|
||||||
|
Ksiazka.cokolwiek # => 'cokolwiek'
|
||||||
|
Ksiazka.new.cokolwiek # => NoMethodError: undefined method `cokolwiek'
|
||||||
|
|
||||||
|
# Gdy włączamy lub rozszerzamy muduły, wykonywane są tzw. wywołania zwrotne
|
||||||
|
|
||||||
|
module PrzykladowyModul
|
||||||
|
def self.included(baza)
|
||||||
|
baza.extend(MotodyKlasowe)
|
||||||
|
baza.send(:include, MetodyInstancji)
|
||||||
|
end
|
||||||
|
|
||||||
|
module MotodyKlasowe
|
||||||
|
def cos
|
||||||
|
'cos'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
module MetodyInstancji
|
||||||
|
def xyz
|
||||||
|
'xyz'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class Cokolwiek
|
||||||
|
include PrzykladowyModul
|
||||||
|
end
|
||||||
|
|
||||||
|
Cokolwiek.cos # => 'cos'
|
||||||
|
Cokolwiek.xyz # => NoMethodError: undefined method `xyz'
|
||||||
|
Cokolwiek.new.cos # => NoMethodError: undefined method `cos'
|
||||||
|
Cokolwiek.new.xyz # => 'qux'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dodatkowe źródła
|
||||||
|
### Polskie
|
||||||
|
|
||||||
|
- [Dokumentacja](https://www.ruby-lang.org/pl/documentation/quickstart/)
|
||||||
|
|
||||||
|
### Angielskie
|
||||||
|
|
||||||
|
- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
|
||||||
|
- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
|
||||||
|
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
|
||||||
|
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
|
||||||
|
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
|
137
pl-pl/xml-pl.html.markdown
Normal file
137
pl-pl/xml-pl.html.markdown
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
---
|
||||||
|
language: xml
|
||||||
|
filename: learnxml-pl.xml
|
||||||
|
contributors:
|
||||||
|
- ["João Farias", "https://github.com/JoaoGFarias"]
|
||||||
|
translators:
|
||||||
|
- ["Tomasz Janiszewski", "https://github.com/janisz"]
|
||||||
|
lang: pl-pl
|
||||||
|
---
|
||||||
|
|
||||||
|
XML (_Extensible Markup Language_) to rozszerzalny język znaczników, stworzony
|
||||||
|
do przechowywania i transportu danych.
|
||||||
|
|
||||||
|
W przeciwieństwie do HTML, XML nie specyfikuje w jaki sposób wyświetlić dane, a
|
||||||
|
tylko je przechowuje.
|
||||||
|
|
||||||
|
* Składnia XML
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<!-- Komentarze w XML wyglądają jak ten -->
|
||||||
|
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<ksiegarnia>
|
||||||
|
<ksiazka kategoria="GOTOWANIE">
|
||||||
|
<tytul lang="pl">Codzienny Włoski</tytul>
|
||||||
|
<autor>Giada De Laurentiis</autor>
|
||||||
|
<rok>2005</rok>
|
||||||
|
<cena>30.00</cena>
|
||||||
|
</ksiazka>
|
||||||
|
<ksiazka kategoria="DZIECI">
|
||||||
|
<tytul lang="pl">Harry Potter</tytul>
|
||||||
|
<autor>J K. Rowling</autor>
|
||||||
|
<rok>2005</rok>
|
||||||
|
<cena>29.99</cena>
|
||||||
|
</ksiazka>
|
||||||
|
<ksiazka kategoria="WEB">
|
||||||
|
<tytul lang="pl">Nauka XML</tytul>
|
||||||
|
<autor>Erik T. Ray</autor>
|
||||||
|
<rok>2003</rok>
|
||||||
|
<cena>39.95</cena>
|
||||||
|
</ksiazka>
|
||||||
|
</ksiegarnia>
|
||||||
|
|
||||||
|
<!-- Powyżej jest typowy plik XML.
|
||||||
|
Zaczyna się od deklaracji zawierającej metadane (opcjonalne).
|
||||||
|
|
||||||
|
XML używa drzewiastej struktury. Powyżej, głównym wierzchołkiem jest
|
||||||
|
'ksiegarnia' , która zawiera trzy (3) węzły potomne, wszystkie 'ksiazki',
|
||||||
|
które zawierają swoje węzły potomne, i tak dalej...
|
||||||
|
|
||||||
|
Węzły są tworzone używające otwierających/zamykających znaczników.
|
||||||
|
Węzły potomne znajdują się pomiędzy otwierającym i zamykającym znacznikiem.
|
||||||
|
-->
|
||||||
|
|
||||||
|
<!-- XML przechowuje dwa typy danych
|
||||||
|
1 - Atrybuty -> metadane o węźle
|
||||||
|
Zazwyczaj parser XML używa tych informacji do przechowywania danych we
|
||||||
|
właściwy sposób. Atrybuty nadawane są poprzez wpisanie ich w otwierajacym
|
||||||
|
znaczniku.
|
||||||
|
2 - Elementy -> to są czyste dane.
|
||||||
|
Dane, które parser otrzymuje z pliku XML.
|
||||||
|
Elementy są deklarowane pomiędzy otwierajacym i zamykającym znacznikiem,
|
||||||
|
bez nawiasów. -->
|
||||||
|
|
||||||
|
<!-- Poniższy element ma dwa atrybuty -->
|
||||||
|
<plik type="gif" id="4293">komputer.gif</plik>
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
* Dobrze sformatowany dokument i walidacja
|
||||||
|
|
||||||
|
Dokument XML jest dobrze sformatowany gdy jest syntaktycznie poprawny.
|
||||||
|
Jednakże możliwe jest wstrzykiwanie większej liczby ograniczeń w dokumencie,
|
||||||
|
używając definicji takich jak DTD i XML Schema.
|
||||||
|
|
||||||
|
Dokument XML, który jest zgodny ze swoją definicją jest poprawny.
|
||||||
|
|
||||||
|
|
||||||
|
Korzystając z tych narzędzi możesz sprawdzić dane zawarte w dokumencie poza
|
||||||
|
logiką aplikacji.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
|
||||||
|
|
||||||
|
<!-- Poniżej jest uproszczona wersja dokumentu księgarni,
|
||||||
|
z dodatkową definicją DTD.-->
|
||||||
|
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE notatka SYSTEM "Ksiegarnia.dtd">
|
||||||
|
<ksiegarnia>
|
||||||
|
<ksiazka kategoria="GOTOWANIE">
|
||||||
|
<tytul >Everyday Italian</tytul>
|
||||||
|
<cena>30.00</cena>
|
||||||
|
</ksiazka>
|
||||||
|
</ksiegarnia>
|
||||||
|
|
||||||
|
<!-- DTD może wyglądać następująco:-->
|
||||||
|
|
||||||
|
<!DOCTYPE notatka
|
||||||
|
[
|
||||||
|
<!ELEMENT ksiegarnia (ksiazka+)>
|
||||||
|
<!ELEMENT ksiazka (tytul,cena)>
|
||||||
|
<!ATTLIST ksiazka kategoria CDATA "Literatura">
|
||||||
|
<!ELEMENT tytul (#PCDATA)>
|
||||||
|
<!ELEMENT cena (#PCDATA)>
|
||||||
|
]>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- DTD zaczyna się od deklaracji
|
||||||
|
Zaczynając od góry, główny węzeł jest zadeklarowany jako wymagający jednego
|
||||||
|
lub więcej węzłów potomnych typu 'ksiżka'.
|
||||||
|
Każda 'ksiażka' powinna zawierać dokładnie jeden 'tytuł' i 'cene' oraz atrybut
|
||||||
|
'kategoria' z 'literaturą' jako wartość domyślna.
|
||||||
|
'tytuł' i 'cena' to pola typu parsowalnych zmiennyc znakowych, co oznacza że
|
||||||
|
użyte znaczniki zostaną zinterpretowane < zamienione <. -->
|
||||||
|
|
||||||
|
<!-- DTD moze być deklarowane wewnątrz pliku XML. -->
|
||||||
|
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
|
||||||
|
<!DOCTYPE notatka
|
||||||
|
[
|
||||||
|
<!ELEMENT ksiegarnia (ksiazka+)>
|
||||||
|
<!ELEMENT ksiazka (tytul,cena)>
|
||||||
|
<!ATTLIST ksiazka kategoria CDATA "Literatura">
|
||||||
|
<!ELEMENT tytul (#PCDATA)>
|
||||||
|
<!ELEMENT cena (#PCDATA)>
|
||||||
|
]>
|
||||||
|
|
||||||
|
<ksiegarnia>
|
||||||
|
<ksiazka kategoria="GOTOWANIE">
|
||||||
|
<tytul >Everyday Italian</tytul>
|
||||||
|
<cena>30.00</cena>
|
||||||
|
</ksiazka>
|
||||||
|
</ksiegarnia>
|
||||||
|
```
|
330
powershell.html.markdown
Normal file
330
powershell.html.markdown
Normal file
@ -0,0 +1,330 @@
|
|||||||
|
---
|
||||||
|
category: tool
|
||||||
|
tool: powershell
|
||||||
|
contributors:
|
||||||
|
- ["Wouter Van Schandevijl", "https://github.com/laoujin"]
|
||||||
|
filename: LearnPowershell.ps1
|
||||||
|
---
|
||||||
|
|
||||||
|
PowerShell is the Windows scripting language and configuration management
|
||||||
|
framework from Microsoft built on the .NET Framework. Windows 7 and up ship
|
||||||
|
with PowerShell.
|
||||||
|
Nearly all examples below can be a part of a shell script or executed directly
|
||||||
|
in the shell.
|
||||||
|
|
||||||
|
A key difference with Bash is that it is mostly objects that you manipulate
|
||||||
|
rather than plain text.
|
||||||
|
|
||||||
|
[Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx)
|
||||||
|
|
||||||
|
If you are uncertain about your environment:
|
||||||
|
|
||||||
|
```
|
||||||
|
Get-ExecutionPolicy -List
|
||||||
|
Set-ExecutionPolicy AllSigned
|
||||||
|
# Execution policies include:
|
||||||
|
# - Restricted: Scripts won't run.
|
||||||
|
# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher.
|
||||||
|
# - AllSigned: Scripts need to be signed by a trusted publisher.
|
||||||
|
# - Unrestricted: Run all scripts.
|
||||||
|
help about_Execution_Policies # for more info
|
||||||
|
|
||||||
|
# Current PowerShell version:
|
||||||
|
$PSVersionTable
|
||||||
|
```
|
||||||
|
|
||||||
|
Getting help:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Find commands
|
||||||
|
Get-Command about_* # alias: gcm
|
||||||
|
Get-Command -Verb Add
|
||||||
|
Get-Alias ps
|
||||||
|
Get-Alias -Definition Get-Process
|
||||||
|
|
||||||
|
Get-Help ps | less # alias: help
|
||||||
|
ps | Get-Member # alias: gm
|
||||||
|
|
||||||
|
Show-Command Get-EventLog # Display GUI to fill in the parameters
|
||||||
|
|
||||||
|
Update-Help # Run as admin
|
||||||
|
```
|
||||||
|
|
||||||
|
The tutorial starts here:
|
||||||
|
|
||||||
|
```
|
||||||
|
# As you already figured, comments start with #
|
||||||
|
|
||||||
|
# Simple hello world example:
|
||||||
|
echo Hello world!
|
||||||
|
# echo is an alias for Write-Output (=cmdlet)
|
||||||
|
# Most cmdlets and functions follow the Verb-Noun naming convention
|
||||||
|
|
||||||
|
# Each command starts on a new line, or after a semicolon:
|
||||||
|
echo 'This is the first line'; echo 'This is the second line'
|
||||||
|
|
||||||
|
# Declaring a variable looks like this:
|
||||||
|
$aString="Some string"
|
||||||
|
# Or like this:
|
||||||
|
$aNumber = 5 -as [double]
|
||||||
|
$aList = 1,2,3,4,5
|
||||||
|
$aString = $aList -join '--' # yes, -split exists also
|
||||||
|
$aHashtable = @{name1='val1'; name2='val2'}
|
||||||
|
|
||||||
|
# Using variables:
|
||||||
|
echo $aString
|
||||||
|
echo "Interpolation: $aString"
|
||||||
|
echo "`$aString has length of $($aString.Length)"
|
||||||
|
echo '$aString'
|
||||||
|
echo @"
|
||||||
|
This is a Here-String
|
||||||
|
$aString
|
||||||
|
"@
|
||||||
|
# Note that ' (single quote) won't expand the variables!
|
||||||
|
# Here-Strings also work with single quote
|
||||||
|
|
||||||
|
# Builtin variables:
|
||||||
|
# There are some useful builtin variables, like
|
||||||
|
echo "Booleans: $TRUE and $FALSE"
|
||||||
|
echo "Empty value: $NULL"
|
||||||
|
echo "Last program's return value: $?"
|
||||||
|
echo "Exit code of last run Windows-based program: $LastExitCode"
|
||||||
|
echo "The last token in the last line received by the session: $$"
|
||||||
|
echo "The first token: $^"
|
||||||
|
echo "Script's PID: $PID"
|
||||||
|
echo "Full path of current script directory: $PSScriptRoot"
|
||||||
|
echo 'Full path of current script: ' + $MyInvocation.MyCommand.Path
|
||||||
|
echo "FUll path of current directory: $Pwd"
|
||||||
|
echo "Bound arguments in a function, script or code block: $PSBoundParameters"
|
||||||
|
echo "Unbound arguments: $($Args -join ', ')."
|
||||||
|
# More builtins: `help about_Automatic_Variables`
|
||||||
|
|
||||||
|
# Inline another file (dot operator)
|
||||||
|
. .\otherScriptName.ps1
|
||||||
|
|
||||||
|
|
||||||
|
### Control Flow
|
||||||
|
# We have the usual if structure:
|
||||||
|
if ($Age -is [string]) {
|
||||||
|
echo 'But.. $Age cannot be a string!'
|
||||||
|
} elseif ($Age -lt 12 -and $Age -gt 0) {
|
||||||
|
echo 'Child (Less than 12. Greater than 0)'
|
||||||
|
} else {
|
||||||
|
echo 'Adult'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Switch statements are more powerfull compared to most languages
|
||||||
|
$val = "20"
|
||||||
|
switch($val) {
|
||||||
|
{ $_ -eq 42 } { "The answer equals 42"; break }
|
||||||
|
'20' { "Exactly 20"; break }
|
||||||
|
{ $_ -like 's*' } { "Case insensitive"; break }
|
||||||
|
{ $_ -clike 's*'} { "clike, ceq, cne for case sensitive"; break }
|
||||||
|
{ $_ -notmatch '^.*$'} { "Regex matching. cnotmatch, cnotlike, ..."; break }
|
||||||
|
{ 'x' -contains 'x'} { "FALSE! -contains is for lists!"; break }
|
||||||
|
default { "Others" }
|
||||||
|
}
|
||||||
|
|
||||||
|
# The classic for
|
||||||
|
for($i = 1; $i -le 10; $i++) {
|
||||||
|
"Loop number $i"
|
||||||
|
}
|
||||||
|
# Or shorter
|
||||||
|
1..10 | % { "Loop number $_" }
|
||||||
|
|
||||||
|
# PowerShell also offers
|
||||||
|
foreach ($var in 'val1','val2','val3') { echo $var }
|
||||||
|
# while () {}
|
||||||
|
# do {} while ()
|
||||||
|
# do {} until ()
|
||||||
|
|
||||||
|
# Exception handling
|
||||||
|
try {} catch {} finally {}
|
||||||
|
try {} catch [System.NullReferenceException] {
|
||||||
|
echo $_.Exception | Format-List -Force
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
### Providers
|
||||||
|
# List files and directories in the current directory
|
||||||
|
ls # or `dir`
|
||||||
|
cd ~ # goto home
|
||||||
|
|
||||||
|
Get-Alias ls # -> Get-ChildItem
|
||||||
|
# Uh!? These cmdlets have generic names because unlike other scripting
|
||||||
|
# languages, PowerShell does not only operate in the current directory.
|
||||||
|
cd HKCU: # go to the HKEY_CURRENT_USER registry hive
|
||||||
|
|
||||||
|
# Get all providers in your session
|
||||||
|
Get-PSProvider
|
||||||
|
|
||||||
|
|
||||||
|
### Pipeline
|
||||||
|
# Cmdlets have parameters that control their execution:
|
||||||
|
Get-ChildItem -Filter *.txt -Name # Get just the name of all txt files
|
||||||
|
# Only need to type as much of a parameter name until it is no longer ambiguous
|
||||||
|
ls -fi *.txt -n # -f is not possible because -Force also exists
|
||||||
|
# Use `Get-Help Get-ChildItem -Full` for a complete overview
|
||||||
|
|
||||||
|
# Results of the previous cmdlet can be passed to the next as input.
|
||||||
|
# `$_` is the current object in the pipeline object.
|
||||||
|
ls | Where-Object { $_.Name -match 'c' } | Export-CSV export.txt
|
||||||
|
ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File export.html
|
||||||
|
|
||||||
|
# If you get confused in the pipeline use `Get-Member` for an overview
|
||||||
|
# of the available methods and properties of the pipelined objects:
|
||||||
|
ls | Get-Member
|
||||||
|
Get-Date | gm
|
||||||
|
|
||||||
|
# ` is the line continuation character. Or end the line with a |
|
||||||
|
Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM `
|
||||||
|
| Stop-Process -WhatIf
|
||||||
|
|
||||||
|
Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List
|
||||||
|
|
||||||
|
# Use % as a shorthand for ForEach-Object
|
||||||
|
(a,b,c) | ForEach-Object `
|
||||||
|
-Begin { "Starting"; $counter = 0 } `
|
||||||
|
-Process { "Processing $_"; $counter++ } `
|
||||||
|
-End { "Finishing: $counter" }
|
||||||
|
|
||||||
|
# Get-Process as a table with three columns
|
||||||
|
# The third column is the value of the VM property in MB and 2 decimal places
|
||||||
|
# Computed columns can be written more verbose as:
|
||||||
|
# `@{name='lbl';expression={$_}`
|
||||||
|
ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize
|
||||||
|
|
||||||
|
|
||||||
|
### Functions
|
||||||
|
# The [string] attribute is optional.
|
||||||
|
function foo([string]$name) {
|
||||||
|
echo "Hey $name, have a function"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Calling your function
|
||||||
|
foo "Say my name"
|
||||||
|
|
||||||
|
# Functions with named parameters, parameter attributes, parsable documention
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Setup a new website
|
||||||
|
.DESCRIPTION
|
||||||
|
Creates everything your new website needs for much win
|
||||||
|
.PARAMETER siteName
|
||||||
|
The name for the new website
|
||||||
|
.EXAMPLE
|
||||||
|
New-Website -Name FancySite -Po 5000
|
||||||
|
New-Website SiteWithDefaultPort
|
||||||
|
New-Website siteName 2000 # ERROR! Port argument could not be validated
|
||||||
|
('name1','name2') | New-Website -Verbose
|
||||||
|
#>
|
||||||
|
function New-Website() {
|
||||||
|
[CmdletBinding()]
|
||||||
|
param (
|
||||||
|
[Parameter(ValueFromPipeline=$true, Mandatory=$true)]
|
||||||
|
[Alias('name')]
|
||||||
|
[string]$siteName,
|
||||||
|
[ValidateSet(3000,5000,8000)]
|
||||||
|
[int]$port = 3000
|
||||||
|
)
|
||||||
|
BEGIN { Write-Verbose 'Creating new website(s)' }
|
||||||
|
PROCESS { echo "name: $siteName, port: $port" }
|
||||||
|
END { Write-Verbose 'Website(s) created' }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
### It's all .NET
|
||||||
|
# A PS string is in fact a .NET System.String
|
||||||
|
# All .NET methods and properties are thus available
|
||||||
|
'string'.ToUpper().Replace('G', 'ggg')
|
||||||
|
# Or more powershellish
|
||||||
|
'string'.ToUpper() -replace 'G', 'ggg'
|
||||||
|
|
||||||
|
# Unsure how that .NET method is called again?
|
||||||
|
'string' | gm
|
||||||
|
|
||||||
|
# Syntax for calling static .NET methods
|
||||||
|
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
|
||||||
|
|
||||||
|
# Note that .NET functions MUST be called with parentheses
|
||||||
|
# while PS functions CANNOT be called with parentheses.
|
||||||
|
# If you do call a cmdlet/PS function with parentheses,
|
||||||
|
# it is the same as passing a single parameter list
|
||||||
|
$writer = New-Object System.IO.StreamWriter($path, $true)
|
||||||
|
$writer.Write([Environment]::NewLine)
|
||||||
|
$writer.Dispose()
|
||||||
|
|
||||||
|
### IO
|
||||||
|
# Reading a value from input:
|
||||||
|
$Name = Read-Host "What's your name?"
|
||||||
|
echo "Hello, $Name!"
|
||||||
|
[int]$Age = Read-Host "What's your age?"
|
||||||
|
|
||||||
|
# Test-Path, Split-Path, Join-Path, Resolve-Path
|
||||||
|
# Get-Content filename # returns a string[]
|
||||||
|
# Set-Content, Add-Content, Clear-Content
|
||||||
|
Get-Command ConvertTo-*,ConvertFrom-*
|
||||||
|
|
||||||
|
|
||||||
|
### Useful stuff
|
||||||
|
# Refresh your PATH
|
||||||
|
$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
|
||||||
|
";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
|
||||||
|
|
||||||
|
# Find Python in path
|
||||||
|
$env:PATH.Split(";") | Where-Object { $_ -like "*python*"}
|
||||||
|
|
||||||
|
# Change working directory without having to remember previous path
|
||||||
|
Push-Location c:\temp # change working directory to c:\temp
|
||||||
|
Pop-Location # change back to previous working directory
|
||||||
|
# Aliases are: pushd and popd
|
||||||
|
|
||||||
|
# Unblock a directory after download
|
||||||
|
Get-ChildItem -Recurse | Unblock-File
|
||||||
|
|
||||||
|
# Open Windows Explorer in working directory
|
||||||
|
ii .
|
||||||
|
|
||||||
|
# Any key to exit
|
||||||
|
$host.UI.RawUI.ReadKey()
|
||||||
|
return
|
||||||
|
|
||||||
|
# Create a shortcut
|
||||||
|
$WshShell = New-Object -comObject WScript.Shell
|
||||||
|
$Shortcut = $WshShell.CreateShortcut($link)
|
||||||
|
$Shortcut.TargetPath = $file
|
||||||
|
$Shortcut.WorkingDirectory = Split-Path $file
|
||||||
|
$Shortcut.Save()
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Configuring your shell
|
||||||
|
|
||||||
|
```
|
||||||
|
# $Profile is the full path for your `Microsoft.PowerShell_profile.ps1`
|
||||||
|
# All code there will be executed when the PS session starts
|
||||||
|
if (-not (Test-Path $Profile)) {
|
||||||
|
New-Item -Type file -Path $Profile -Force
|
||||||
|
notepad $Profile
|
||||||
|
}
|
||||||
|
# More info: `help about_profiles`
|
||||||
|
# For a more usefull shell, be sure to check the project PSReadLine below
|
||||||
|
```
|
||||||
|
|
||||||
|
Interesting Projects
|
||||||
|
|
||||||
|
* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials
|
||||||
|
* [PSGet](https://github.com/psget/psget) NuGet for PowerShell
|
||||||
|
* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)
|
||||||
|
* [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!)
|
||||||
|
* [PSake](https://github.com/psake/psake) Build automation tool
|
||||||
|
* [Pester](https://github.com/pester/Pester) BDD Testing Framework
|
||||||
|
* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind
|
||||||
|
* [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead)
|
||||||
|
|
||||||
|
Not covered
|
||||||
|
|
||||||
|
* WMI: Windows Management Intrumentation (Get-CimInstance)
|
||||||
|
* Multitasking: Start-Job -scriptBlock {...},
|
||||||
|
* Code Signing
|
||||||
|
* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command)
|
@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
language: brainfuck
|
language: bf
|
||||||
contributors:
|
contributors:
|
||||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user