mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-11-22 21:52:31 +03:00
Merge branch 'master' into master
This commit is contained in:
commit
4a7d678c25
@ -81,7 +81,7 @@ supports R5RS and R7RS (work in progress) standards and many extensions.
|
||||
(string-append "pine" "apple") ;; => "pineapple"
|
||||
(string-ref "tapioca" 3) ;; => #\i;; character 'i' is at index 3
|
||||
(string->list "CHICKEN") ;; => (#\C #\H #\I #\C #\K #\E #\N)
|
||||
(string->intersperse '("1" "2") ":") ;; => "1:2"
|
||||
(string-intersperse '("1" "2") ":") ;; => "1:2"
|
||||
(string-split "1:2:3" ":") ;; => ("1" "2" "3")
|
||||
|
||||
|
||||
|
@ -1,3 +1,12 @@
|
||||
## Is this a major issue that you cannot fix?
|
||||
|
||||
**Being a community driven documents of languages and tools,"YOUR" contributions
|
||||
are also important.
|
||||
If the issue you're reporting is trivial to report to maintainers why not contribute
|
||||
to fix it. In that way, you will have contributed to an awesome open-source project.
|
||||
The changes can be typo fix, fixing of data in examples or grammar fix. If you found it,
|
||||
why not do it and take full credit for it?**
|
||||
|
||||
Make sure the issue title is prepended with '[language/lang-code]' if the language is
|
||||
already on the site.
|
||||
If it's a request for a new language, use: '[Request] [language/lang-code]'
|
||||
|
@ -155,7 +155,7 @@ Small-o, commonly written as **o**, is an Asymptotic Notation to denote the
|
||||
upper bound (that is not asymptotically tight) on the growth rate of runtime
|
||||
of an algorithm.
|
||||
|
||||
`f(n)` is o(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is < `c g(n)`
|
||||
`f(n)` is o(g(n)), if for all real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is < `c g(n)`
|
||||
for every input size n (n > n<sub>0</sub>).
|
||||
|
||||
The definitions of O-notation and o-notation are similar. The main difference
|
||||
@ -168,7 +168,7 @@ Small-omega, commonly written as **ω**, is an Asymptotic Notation to denote
|
||||
the lower bound (that is not asymptotically tight) on the growth rate of
|
||||
runtime of an algorithm.
|
||||
|
||||
`f(n)` is ω(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is > `c g(n)`
|
||||
`f(n)` is ω(g(n)), if for all real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is > `c g(n)`
|
||||
for every input size n (n > n<sub>0</sub>).
|
||||
|
||||
The definitions of Ω-notation and ω-notation are similar. The main difference
|
||||
|
@ -6,14 +6,15 @@ contributors:
|
||||
|
||||
---
|
||||
|
||||
AWK is a standard tool on every POSIX-compliant UNIX system. It's like a
|
||||
stripped-down Perl, perfect for text-processing tasks and other scripting
|
||||
needs. It has a C-like syntax, but without semicolons, manual memory
|
||||
management, or static typing. It excels at text processing. You can call to it
|
||||
from a shell script, or you can use it as a stand-alone scripting language.
|
||||
AWK is a standard tool on every POSIX-compliant UNIX system. It's like
|
||||
flex/lex, from the command-line, perfect for text-processing tasks and
|
||||
other scripting needs. It has a C-like syntax, but without mandatory
|
||||
semicolons (although, you should use them anyway, because they are required
|
||||
when you're writing one-liners, something AWK excells at), manual memory
|
||||
management, or static typing. It excels at text processing. You can call to
|
||||
it from a shell script, or you can use it as a stand-alone scripting language.
|
||||
|
||||
Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always
|
||||
count on it, whereas Perl's future is in question. AWK is also easier to read
|
||||
Why use AWK instead of Perl? Readability. AWK is easier to read
|
||||
than Perl. For simple text-processing scripts, particularly ones that read
|
||||
files line by line and split on delimiters, AWK is probably the right tool for
|
||||
the job.
|
||||
@ -23,8 +24,23 @@ the job.
|
||||
|
||||
# Comments are like this
|
||||
|
||||
# AWK programs consist of a collection of patterns and actions. The most
|
||||
# important pattern is called BEGIN. Actions go into brace blocks.
|
||||
|
||||
# AWK programs consist of a collection of patterns and actions.
|
||||
pattern1 { action; } # just like lex
|
||||
pattern2 { action; }
|
||||
|
||||
# There is an implied loop and AWK automatically reads and parses each
|
||||
# record of each file supplied. Each record is split by the FS delimiter,
|
||||
# which defaults to white-space (multiple spaces,tabs count as one)
|
||||
# You cann assign FS either on the command line (-F C) or in your BEGIN
|
||||
# pattern
|
||||
|
||||
# One of the special patterns is BEGIN. The BEGIN pattern is true
|
||||
# BEFORE any of the files are read. The END pattern is true after
|
||||
# an End-of-file from the last file (or standard-in if no files specified)
|
||||
# There is also an output field separator (OFS) that you can assign, which
|
||||
# defaults to a single space
|
||||
|
||||
BEGIN {
|
||||
|
||||
# BEGIN will run at the beginning of the program. It's where you put all
|
||||
@ -32,114 +48,116 @@ BEGIN {
|
||||
# have no text files, then think of BEGIN as the main entry point.
|
||||
|
||||
# Variables are global. Just set them or use them, no need to declare..
|
||||
count = 0
|
||||
count = 0;
|
||||
|
||||
# Operators just like in C and friends
|
||||
a = count + 1
|
||||
b = count - 1
|
||||
c = count * 1
|
||||
d = count / 1 # integer division
|
||||
e = count % 1 # modulus
|
||||
f = count ^ 1 # exponentiation
|
||||
a = count + 1;
|
||||
b = count - 1;
|
||||
c = count * 1;
|
||||
d = count / 1; # integer division
|
||||
e = count % 1; # modulus
|
||||
f = count ^ 1; # exponentiation
|
||||
|
||||
a += 1
|
||||
b -= 1
|
||||
c *= 1
|
||||
d /= 1
|
||||
e %= 1
|
||||
f ^= 1
|
||||
a += 1;
|
||||
b -= 1;
|
||||
c *= 1;
|
||||
d /= 1;
|
||||
e %= 1;
|
||||
f ^= 1;
|
||||
|
||||
# Incrementing and decrementing by one
|
||||
a++
|
||||
b--
|
||||
a++;
|
||||
b--;
|
||||
|
||||
# As a prefix operator, it returns the incremented value
|
||||
++a
|
||||
--b
|
||||
++a;
|
||||
--b;
|
||||
|
||||
# Notice, also, no punctuation such as semicolons to terminate statements
|
||||
|
||||
# Control statements
|
||||
if (count == 0)
|
||||
print "Starting with count of 0"
|
||||
print "Starting with count of 0";
|
||||
else
|
||||
print "Huh?"
|
||||
print "Huh?";
|
||||
|
||||
# Or you could use the ternary operator
|
||||
print (count == 0) ? "Starting with count of 0" : "Huh?"
|
||||
print (count == 0) ? "Starting with count of 0" : "Huh?";
|
||||
|
||||
# Blocks consisting of multiple lines use braces
|
||||
while (a < 10) {
|
||||
print "String concatenation is done" " with a series" " of"
|
||||
" space-separated strings"
|
||||
print a
|
||||
" space-separated strings";
|
||||
print a;
|
||||
|
||||
a++
|
||||
a++;
|
||||
}
|
||||
|
||||
for (i = 0; i < 10; i++)
|
||||
print "Good ol' for loop"
|
||||
print "Good ol' for loop";
|
||||
|
||||
# As for comparisons, they're the standards:
|
||||
a < b # Less than
|
||||
a <= b # Less than or equal
|
||||
a != b # Not equal
|
||||
a == b # Equal
|
||||
a > b # Greater than
|
||||
a >= b # Greater than or equal
|
||||
# a < b # Less than
|
||||
# a <= b # Less than or equal
|
||||
# a != b # Not equal
|
||||
# a == b # Equal
|
||||
# a > b # Greater than
|
||||
# a >= b # Greater than or equal
|
||||
|
||||
# Logical operators as well
|
||||
a && b # AND
|
||||
a || b # OR
|
||||
# a && b # AND
|
||||
# a || b # OR
|
||||
|
||||
# In addition, there's the super useful regular expression match
|
||||
if ("foo" ~ "^fo+$")
|
||||
print "Fooey!"
|
||||
print "Fooey!";
|
||||
if ("boo" !~ "^fo+$")
|
||||
print "Boo!"
|
||||
print "Boo!";
|
||||
|
||||
# Arrays
|
||||
arr[0] = "foo"
|
||||
arr[1] = "bar"
|
||||
# Unfortunately, there is no other way to initialize an array. Ya just
|
||||
# gotta chug through every value line by line like that.
|
||||
|
||||
# You also have associative arrays
|
||||
assoc["foo"] = "bar"
|
||||
assoc["bar"] = "baz"
|
||||
arr[0] = "foo";
|
||||
arr[1] = "bar";
|
||||
|
||||
# You can also initialize an array with the built-in function split()
|
||||
|
||||
n = split("foo:bar:baz", arr, ":");
|
||||
|
||||
# You also have associative arrays (actually, they're all associative arrays)
|
||||
assoc["foo"] = "bar";
|
||||
assoc["bar"] = "baz";
|
||||
|
||||
# And multi-dimensional arrays, with some limitations I won't mention here
|
||||
multidim[0,0] = "foo"
|
||||
multidim[0,1] = "bar"
|
||||
multidim[1,0] = "baz"
|
||||
multidim[1,1] = "boo"
|
||||
multidim[0,0] = "foo";
|
||||
multidim[0,1] = "bar";
|
||||
multidim[1,0] = "baz";
|
||||
multidim[1,1] = "boo";
|
||||
|
||||
# You can test for array membership
|
||||
if ("foo" in assoc)
|
||||
print "Fooey!"
|
||||
print "Fooey!";
|
||||
|
||||
# You can also use the 'in' operator to traverse the keys of an array
|
||||
for (key in assoc)
|
||||
print assoc[key]
|
||||
print assoc[key];
|
||||
|
||||
# The command line is in a special array called ARGV
|
||||
for (argnum in ARGV)
|
||||
print ARGV[argnum]
|
||||
print ARGV[argnum];
|
||||
|
||||
# You can remove elements of an array
|
||||
# This is particularly useful to prevent AWK from assuming the arguments
|
||||
# are files for it to process
|
||||
delete ARGV[1]
|
||||
delete ARGV[1];
|
||||
|
||||
# The number of command line arguments is in a variable called ARGC
|
||||
print ARGC
|
||||
print ARGC;
|
||||
|
||||
# AWK has several built-in functions. They fall into three categories. I'll
|
||||
# demonstrate each of them in their own functions, defined later.
|
||||
|
||||
return_value = arithmetic_functions(a, b, c)
|
||||
string_functions()
|
||||
io_functions()
|
||||
return_value = arithmetic_functions(a, b, c);
|
||||
string_functions();
|
||||
io_functions();
|
||||
}
|
||||
|
||||
# Here's how you define a function
|
||||
@ -159,26 +177,26 @@ function arithmetic_functions(a, b, c, d) {
|
||||
# Now, to demonstrate the arithmetic functions
|
||||
|
||||
# Most AWK implementations have some standard trig functions
|
||||
localvar = sin(a)
|
||||
localvar = cos(a)
|
||||
localvar = atan2(a, b) # arc tangent of b / a
|
||||
localvar = sin(a);
|
||||
localvar = cos(a);
|
||||
localvar = atan2(b, a); # arc tangent of b / a
|
||||
|
||||
# And logarithmic stuff
|
||||
localvar = exp(a)
|
||||
localvar = log(a)
|
||||
localvar = exp(a);
|
||||
localvar = log(a);
|
||||
|
||||
# Square root
|
||||
localvar = sqrt(a)
|
||||
localvar = sqrt(a);
|
||||
|
||||
# Truncate floating point to integer
|
||||
localvar = int(5.34) # localvar => 5
|
||||
localvar = int(5.34); # localvar => 5
|
||||
|
||||
# Random numbers
|
||||
srand() # Supply a seed as an argument. By default, it uses the time of day
|
||||
localvar = rand() # Random number between 0 and 1.
|
||||
srand(); # Supply a seed as an argument. By default, it uses the time of day
|
||||
localvar = rand(); # Random number between 0 and 1.
|
||||
|
||||
# Here's how to return a value
|
||||
return localvar
|
||||
return localvar;
|
||||
}
|
||||
|
||||
function string_functions( localvar, arr) {
|
||||
@ -188,61 +206,66 @@ function string_functions( localvar, arr) {
|
||||
|
||||
# Search and replace, first instance (sub) or all instances (gsub)
|
||||
# Both return number of matches replaced
|
||||
localvar = "fooooobar"
|
||||
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
|
||||
gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
|
||||
localvar = "fooooobar";
|
||||
sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar"
|
||||
gsub("e+", ".", localvar); # localvar => "m..t m. at th. bar"
|
||||
|
||||
# Search for a string that matches a regular expression
|
||||
# index() does the same thing, but doesn't allow a regular expression
|
||||
match(localvar, "t") # => 4, since the 't' is the fourth character
|
||||
match(localvar, "t"); # => 4, since the 't' is the fourth character
|
||||
|
||||
# Split on a delimiter
|
||||
split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"]
|
||||
n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
|
||||
|
||||
# Other useful stuff
|
||||
sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3"
|
||||
substr("foobar", 2, 3) # => "oob"
|
||||
substr("foobar", 4) # => "bar"
|
||||
length("foo") # => 3
|
||||
tolower("FOO") # => "foo"
|
||||
toupper("foo") # => "FOO"
|
||||
sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3"
|
||||
substr("foobar", 2, 3); # => "oob"
|
||||
substr("foobar", 4); # => "bar"
|
||||
length("foo"); # => 3
|
||||
tolower("FOO"); # => "foo"
|
||||
toupper("foo"); # => "FOO"
|
||||
}
|
||||
|
||||
function io_functions( localvar) {
|
||||
|
||||
# You've already seen print
|
||||
print "Hello world"
|
||||
print "Hello world";
|
||||
|
||||
# There's also printf
|
||||
printf("%s %d %d %d\n", "Testing", 1, 2, 3)
|
||||
printf("%s %d %d %d\n", "Testing", 1, 2, 3);
|
||||
|
||||
# AWK doesn't have file handles, per se. It will automatically open a file
|
||||
# handle for you when you use something that needs one. The string you used
|
||||
# for this can be treated as a file handle, for purposes of I/O. This makes
|
||||
# it feel sort of like shell scripting:
|
||||
# it feel sort of like shell scripting, but to get the same output, the string
|
||||
# must match exactly, so use a vaiable:
|
||||
|
||||
outfile = "/tmp/foobar.txt";
|
||||
|
||||
print "foobar" >"/tmp/foobar.txt"
|
||||
print "foobar" > outfile;
|
||||
|
||||
# Now the string "/tmp/foobar.txt" is a file handle. You can close it:
|
||||
close("/tmp/foobar.txt")
|
||||
# Now the string outfile is a file handle. You can close it:
|
||||
close(outfile);
|
||||
|
||||
# Here's how you run something in the shell
|
||||
system("echo foobar") # => prints foobar
|
||||
system("echo foobar"); # => prints foobar
|
||||
|
||||
# Reads a line from standard input and stores in localvar
|
||||
getline localvar
|
||||
getline localvar;
|
||||
|
||||
# Reads a line from a pipe
|
||||
"echo foobar" | getline localvar # localvar => "foobar"
|
||||
close("echo foobar")
|
||||
# Reads a line from a pipe (again, use a string so you close it properly)
|
||||
cmd = "echo foobar";
|
||||
cmd | getline localvar; # localvar => "foobar"
|
||||
close(cmd);
|
||||
|
||||
# Reads a line from a file and stores in localvar
|
||||
getline localvar <"/tmp/foobar.txt"
|
||||
close("/tmp/foobar.txt")
|
||||
infile = "/tmp/foobar.txt";
|
||||
getline localvar < infile;
|
||||
close(infile);
|
||||
}
|
||||
|
||||
# As I said at the beginning, AWK programs consist of a collection of patterns
|
||||
# and actions. You've already seen the all-important BEGIN pattern. Other
|
||||
# and actions. You've already seen the BEGIN pattern. Other
|
||||
# patterns are used only if you're processing lines from files or standard
|
||||
# input.
|
||||
#
|
||||
@ -257,7 +280,7 @@ function io_functions( localvar) {
|
||||
# expression, /^fo+bar$/, and will be skipped for any line that fails to
|
||||
# match it. Let's just print the line:
|
||||
|
||||
print
|
||||
print;
|
||||
|
||||
# Whoa, no argument! That's because print has a default argument: $0.
|
||||
# $0 is the name of the current line being processed. It is created
|
||||
@ -268,16 +291,16 @@ function io_functions( localvar) {
|
||||
# does. And, like the shell, each field can be access with a dollar sign
|
||||
|
||||
# This will print the second and fourth fields in the line
|
||||
print $2, $4
|
||||
print $2, $4;
|
||||
|
||||
# AWK automatically defines many other variables to help you inspect and
|
||||
# process each line. The most important one is NF
|
||||
|
||||
# Prints the number of fields on this line
|
||||
print NF
|
||||
print NF;
|
||||
|
||||
# Print the last field on this line
|
||||
print $NF
|
||||
print $NF;
|
||||
}
|
||||
|
||||
# Every pattern is actually a true/false test. The regular expression in the
|
||||
@ -286,7 +309,7 @@ function io_functions( localvar) {
|
||||
# currently processing. Thus, the complete version of it is this:
|
||||
|
||||
$0 ~ /^fo+bar$/ {
|
||||
print "Equivalent to the last pattern"
|
||||
print "Equivalent to the last pattern";
|
||||
}
|
||||
|
||||
a > 0 {
|
||||
@ -315,10 +338,10 @@ a > 0 {
|
||||
BEGIN {
|
||||
|
||||
# First, ask the user for the name
|
||||
print "What name would you like the average age for?"
|
||||
print "What name would you like the average age for?";
|
||||
|
||||
# Get a line from standard input, not from files on the command line
|
||||
getline name <"/dev/stdin"
|
||||
getline name < "/dev/stdin";
|
||||
}
|
||||
|
||||
# Now, match every line whose first field is the given name
|
||||
@ -335,8 +358,8 @@ $1 == name {
|
||||
# ...etc. There are plenty more, documented in the man page.
|
||||
|
||||
# Keep track of a running total and how many lines matched
|
||||
sum += $3
|
||||
nlines++
|
||||
sum += $3;
|
||||
nlines++;
|
||||
}
|
||||
|
||||
# Another special pattern is called END. It will run after processing all the
|
||||
@ -348,7 +371,7 @@ $1 == name {
|
||||
|
||||
END {
|
||||
if (nlines)
|
||||
print "The average age for " name " is " sum / nlines
|
||||
print "The average age for " name " is " sum / nlines;
|
||||
}
|
||||
|
||||
```
|
||||
@ -357,3 +380,4 @@ Further Reading:
|
||||
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
|
||||
* [Awk man page](https://linux.die.net/man/1/awk)
|
||||
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems.
|
||||
* [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html)
|
||||
|
@ -26,7 +26,7 @@ Nearly all examples below can be a part of a shell script or executed directly i
|
||||
[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html)
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
#!/usr/bin/env bash
|
||||
# First line of the script is shebang which tells the system how to execute
|
||||
# the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
|
||||
# As you already figured, comments start with #. Shebang is also a comment.
|
||||
@ -89,6 +89,25 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
|
||||
# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
|
||||
# Note that it only returns default value and doesn't change variable value.
|
||||
|
||||
# Declare an array with 6 elements
|
||||
array0=(one two three four five six)
|
||||
# Print first element
|
||||
echo $array0 # => "one"
|
||||
# Print first element
|
||||
echo ${array0[0]} # => "one"
|
||||
# Print all elements
|
||||
echo ${array0[@]} # => "one two three four five six"
|
||||
# Print number of elements
|
||||
echo ${#array0[@]} # => "6"
|
||||
# Print number of characters in third element
|
||||
echo ${#array0[2]} # => "5"
|
||||
# Print 2 elements starting from forth
|
||||
echo ${array0[@]:3:2} # => "four five"
|
||||
# Print all elements. Each of them on new line.
|
||||
for i in "${array0[@]}"; do
|
||||
echo "$i"
|
||||
done
|
||||
|
||||
# Brace Expansion { }
|
||||
# Used to generate arbitrary strings
|
||||
echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
|
||||
@ -171,6 +190,13 @@ fi
|
||||
# which are subtly different from single [ ].
|
||||
# See http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
|
||||
|
||||
# Redefine command 'ping' as alias to send only 5 packets
|
||||
alias ping='ping -c 5'
|
||||
# Escape alias and use command with this name instead
|
||||
\ping 192.168.1.1
|
||||
# Print all aliases
|
||||
alias -p
|
||||
|
||||
# Expressions are denoted with the following format:
|
||||
echo $(( 10 + 5 )) # => 15
|
||||
|
||||
@ -218,10 +244,13 @@ mv s0urc3.txt dst.txt # sorry, l33t hackers...
|
||||
# Since bash works in the context of a current directory, you might want to
|
||||
# run your command in some other directory. We have cd for changing location:
|
||||
cd ~ # change to home directory
|
||||
cd # also goes to home directory
|
||||
cd .. # go up one directory
|
||||
# (^^say, from /home/username/Downloads to /home/username)
|
||||
cd /home/username/Documents # change to specified directory
|
||||
cd ~/Documents/.. # still in home directory..isn't it??
|
||||
cd - # change to last directory
|
||||
# => /home/username/Documents
|
||||
|
||||
# Use subshells to work across directories
|
||||
(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD")
|
||||
@ -246,6 +275,7 @@ print("#stderr", file=sys.stderr)
|
||||
for line in sys.stdin:
|
||||
print(line, file=sys.stdout)
|
||||
EOF
|
||||
# Variables will be expanded if the first "EOF" is not quoted
|
||||
|
||||
# Run the hello.py Python script with various stdin, stdout, and
|
||||
# stderr redirections:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: "Brainfuck"
|
||||
filename: brainfuck.bf
|
||||
language: bf
|
||||
filename: bf.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -71,10 +71,16 @@ void func(); // function which may accept any number of arguments
|
||||
// Use nullptr instead of NULL in C++
|
||||
int* ip = nullptr;
|
||||
|
||||
// C standard headers are available in C++,
|
||||
// but are prefixed with "c" and have no .h suffix.
|
||||
// C standard headers are available in C++.
|
||||
// C headers end in .h, while
|
||||
// C++ headers are prefixed with "c" and have no ".h" suffix.
|
||||
|
||||
// The C++ standard version:
|
||||
#include <cstdio>
|
||||
|
||||
//The C standard version:
|
||||
#include <stdio.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
printf("Hello, world!\n");
|
||||
@ -1051,6 +1057,8 @@ cout << ST.size(); // will print the size of set ST
|
||||
// Output: 0
|
||||
|
||||
// NOTE: for duplicate elements we can use multiset
|
||||
// NOTE: For hash sets, use unordered_set. They are more efficient but
|
||||
// do not preserve order. unordered_set is available since C++11
|
||||
|
||||
// Map
|
||||
// Maps store elements formed by a combination of a key value
|
||||
@ -1078,6 +1086,8 @@ cout << it->second;
|
||||
|
||||
// Output: 26
|
||||
|
||||
// NOTE: For hash maps, use unordered_map. They are more efficient but do
|
||||
// not preserve order. unordered_map is available since C++11.
|
||||
|
||||
///////////////////////////////////
|
||||
// Logical and Bitwise operators
|
||||
@ -1127,7 +1137,6 @@ compl 4 // Performs a bitwise not
|
||||
```
|
||||
Further Reading:
|
||||
|
||||
An up-to-date language reference can be found at
|
||||
<http://cppreference.com/w/cpp>
|
||||
|
||||
Additional resources may be found at <http://cplusplus.com>
|
||||
* An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp).
|
||||
* Additional resources may be found at [CPlusPlus](http://cplusplus.com).
|
||||
* A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb).
|
||||
|
@ -8,6 +8,8 @@ contributors:
|
||||
- ["Marco Scannadinari", "https://marcoms.github.io"]
|
||||
- ["Zachary Ferguson", "https://github.io/zfergus2"]
|
||||
- ["himanshu", "https://github.com/himanshu81494"]
|
||||
- ["Joshua Li", "https://github.com/JoshuaRLi"]
|
||||
- ["Dragos B. Chirila", "https://github.com/dchirila"]
|
||||
---
|
||||
|
||||
Ah, C. Still **the** language of modern high-performance computing.
|
||||
@ -17,13 +19,14 @@ it more than makes up for it with raw speed. Just be aware of its manual
|
||||
memory management and C will take you as far as you need to go.
|
||||
|
||||
> **About compiler flags**
|
||||
>
|
||||
> By default, gcc and clang are pretty quiet about compilation warnings and
|
||||
> errors, which can be very useful information. Using some
|
||||
> stricter compiler flags is recommended. Here is an example you can
|
||||
> tweak to your liking:
|
||||
>
|
||||
> `-Wall -Wextra -Werror -O0 -ansi -pedantic -std=c11`
|
||||
> By default, gcc and clang are pretty quiet about compilation warnings and
|
||||
> errors, which can be very useful information. Explicitly using stricter
|
||||
> compiler flags is recommended. Here are some recommended defaults:
|
||||
>
|
||||
> `-Wall -Wextra -Werror -O2 -std=c99 -pedantic`
|
||||
>
|
||||
> For information on what these flags do as well as other flags, consult the man page for your C compiler (e.g. `man 1 gcc`) or just search online.
|
||||
|
||||
```c
|
||||
// Single-line comments start with // - only available in C99 and later.
|
||||
@ -87,6 +90,8 @@ int main (int argc, char** argv)
|
||||
|
||||
// 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
|
||||
// (however, C99-compliant compilers allow declarations near the point where
|
||||
// the value is used)
|
||||
|
||||
// ints are usually 4 bytes
|
||||
int x_int = 0;
|
||||
@ -99,7 +104,7 @@ int main (int argc, char** argv)
|
||||
char y_char = 'y'; // Char literals are quoted with ''
|
||||
|
||||
// longs are often 4 to 8 bytes; long longs are guaranteed to be at least
|
||||
// 64 bits
|
||||
// 8 bytes
|
||||
long x_long = 0;
|
||||
long long x_long_long = 0;
|
||||
|
||||
@ -139,6 +144,17 @@ int main (int argc, char** argv)
|
||||
|
||||
// You can initialize an array to 0 thusly:
|
||||
char my_array[20] = {0};
|
||||
// where the "{0}" part is called an "array initializer".
|
||||
// NOTE that you get away without explicitly declaring the size of the array,
|
||||
// IF you initialize the array on the same line. So, the following declaration
|
||||
// is equivalent:
|
||||
char my_array[] = {0};
|
||||
// BUT, then you have to evaluate the size of the array at run-time, like this:
|
||||
size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]);
|
||||
// WARNING If you adopt this approach, you should evaluate the size *before*
|
||||
// you begin passing the array to function (see later discussion), because
|
||||
// arrays get "downgraded" to raw pointers when they are passed to functions
|
||||
// (so the statement above will produce the wrong result inside the function).
|
||||
|
||||
// Indexing an array is like other languages -- or,
|
||||
// rather, other languages are like C
|
||||
@ -372,8 +388,8 @@ int main (int argc, char** argv)
|
||||
// respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from <limits.h>
|
||||
|
||||
// Integral types can be cast to floating-point types, and vice-versa.
|
||||
printf("%f\n", (float)100); // %f formats a float
|
||||
printf("%lf\n", (double)100); // %lf formats a double
|
||||
printf("%f\n", (double) 100); // %f always formats a double...
|
||||
printf("%f\n", (float) 100); // ...even with a float.
|
||||
printf("%d\n", (char)100.0);
|
||||
|
||||
///////////////////////////////////////
|
||||
@ -431,7 +447,7 @@ int main (int argc, char** argv)
|
||||
// or when it's the argument of the `sizeof` or `alignof` operator:
|
||||
int arraythethird[10];
|
||||
int *ptr = arraythethird; // equivalent with int *ptr = &arr[0];
|
||||
printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr);
|
||||
printf("%zu, %zu\n", sizeof(arraythethird), sizeof(ptr));
|
||||
// probably prints "40, 4" or "40, 8"
|
||||
|
||||
// Pointers are incremented and decremented based on their type
|
||||
@ -447,7 +463,7 @@ int main (int argc, char** argv)
|
||||
for (xx = 0; xx < 20; xx++) {
|
||||
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
|
||||
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
|
||||
|
||||
|
||||
// Be careful passing user-provided values to malloc! If you want
|
||||
// to be safe, you can use calloc instead (which, unlike malloc, also zeros out the memory)
|
||||
int* my_other_ptr = calloc(20, sizeof(int));
|
||||
@ -520,9 +536,11 @@ Example: in-place string reversal
|
||||
void str_reverse(char *str_in)
|
||||
{
|
||||
char tmp;
|
||||
int ii = 0;
|
||||
size_t ii = 0;
|
||||
size_t len = strlen(str_in); // `strlen()` is part of the c standard library
|
||||
for (ii = 0; ii < len / 2; ii++) {
|
||||
// NOTE: length returned by `strlen` DOESN'T include the
|
||||
// terminating NULL byte ('\0')
|
||||
for (ii = 0; ii < len / 2; ii++) { // in C99 you can directly declare type of `ii` here
|
||||
tmp = str_in[ii];
|
||||
str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
|
||||
str_in[len - ii - 1] = tmp;
|
||||
@ -587,6 +605,14 @@ static int j = 0; //other files using testFunc2() cannot access variable j
|
||||
void testFunc2() {
|
||||
extern int j;
|
||||
}
|
||||
// The static keyword makes a variable inaccessible to code outside the
|
||||
// compilation unit. (On almost all systems, a "compilation unit" is a .c
|
||||
// file.) static can apply both to global (to the compilation unit) variables,
|
||||
// functions, and function-local variables. When using static with
|
||||
// function-local variables, the variable is effectively global and retains its
|
||||
// value across function calls, but is only accessible within the function it
|
||||
// is declared in. Additionally, static variables are initialized to 0 if not
|
||||
// declared with some other starting value.
|
||||
//**You may also declare functions as static to make them private**
|
||||
|
||||
///////////////////////////////////////
|
||||
@ -701,7 +727,8 @@ typedef void (*my_fnp_type)(char *);
|
||||
"%3.2f"; // minimum 3 digits left and 2 digits right decimal float
|
||||
"%7.4s"; // (can do with strings too)
|
||||
"%c"; // char
|
||||
"%p"; // pointer
|
||||
"%p"; // pointer. NOTE: need to (void *)-cast the pointer, before passing
|
||||
// it as an argument to `printf`.
|
||||
"%x"; // hexadecimal
|
||||
"%o"; // octal
|
||||
"%%"; // prints %
|
||||
|
@ -100,7 +100,7 @@ writeln(varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg);
|
||||
// be made to alias a variable other than the variable it is initialized with.
|
||||
// Here, refToActual refers to actual.
|
||||
var actual = 10;
|
||||
ref refToActual = actual;
|
||||
ref refToActual = actual;
|
||||
writeln(actual, " == ", refToActual); // prints the same value
|
||||
actual = -123; // modify actual (which refToActual refers to)
|
||||
writeln(actual, " == ", refToActual); // prints the same value
|
||||
@ -444,7 +444,7 @@ arrayFromLoop = [value in arrayFromLoop] value + 1;
|
||||
|
||||
// Procedures
|
||||
|
||||
// Chapel procedures have similar syntax functions in other languages.
|
||||
// Chapel procedures have similar syntax functions in other languages.
|
||||
proc fibonacci(n : int) : int {
|
||||
if n <= 1 then return n;
|
||||
return fibonacci(n-1) + fibonacci(n-2);
|
||||
@ -893,7 +893,6 @@ foo();
|
||||
// We can declare a main procedure, but all the code above main still gets
|
||||
// executed.
|
||||
proc main() {
|
||||
writeln("PARALLELISM START");
|
||||
|
||||
// A begin statement will spin the body of that statement off
|
||||
// into one new task.
|
||||
@ -1141,11 +1140,13 @@ to see if more topics have been added or more tutorials created.
|
||||
Your input, questions, and discoveries are important to the developers!
|
||||
-----------------------------------------------------------------------
|
||||
|
||||
The Chapel language is still in-development (version 1.16.0), so there are
|
||||
The Chapel language is still in active development, so there are
|
||||
occasional hiccups with performance and language features. The more information
|
||||
you give the Chapel development team about issues you encounter or features you
|
||||
would like to see, the better the language becomes. Feel free to email the team
|
||||
and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman).
|
||||
would like to see, the better the language becomes.
|
||||
There are several ways to interact with the developers:
|
||||
+ [Gitter chat](https://gitter.im/chapel-lang/chapel)
|
||||
+ [sourceforge email lists](https://sourceforge.net/p/chapel/mailman)
|
||||
|
||||
If you're really interested in the development of the compiler or contributing
|
||||
to the project, [check out the master GitHub repository](https://github.com/chapel-lang/chapel).
|
||||
@ -1154,12 +1155,14 @@ It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
Installing the Compiler
|
||||
-----------------------
|
||||
|
||||
[The Official Chapel documentation details how to download and compile the Chapel compiler.](https://chapel-lang.org/docs/usingchapel/QUICKSTART.html)
|
||||
|
||||
Chapel can be built and installed on your average 'nix machine (and cygwin).
|
||||
[Download the latest release version](https://github.com/chapel-lang/chapel/releases/)
|
||||
and it's as easy as
|
||||
|
||||
1. `tar -xvf chapel-1.16.0.tar.gz`
|
||||
2. `cd chapel-1.16.0`
|
||||
1. `tar -xvf chapel-<VERSION>.tar.gz`
|
||||
2. `cd chapel-<VERSION>`
|
||||
3. `source util/setchplenv.bash # or .sh or .csh or .fish`
|
||||
4. `make`
|
||||
5. `make check # optional`
|
||||
|
212
citron.html.markdown
Normal file
212
citron.html.markdown
Normal file
@ -0,0 +1,212 @@
|
||||
---
|
||||
language: citron
|
||||
filename: learncitron.ctr
|
||||
contributors:
|
||||
- ["AnotherTest", ""]
|
||||
lang: en-us
|
||||
---
|
||||
```ruby
|
||||
# Comments start with a '#'
|
||||
# All comments encompass a single line
|
||||
|
||||
###########################################
|
||||
## 1. Primitive Data types and Operators
|
||||
###########################################
|
||||
|
||||
# You have numbers
|
||||
3. # 3
|
||||
|
||||
# Numbers are all doubles in interpreted mode
|
||||
|
||||
# Mathematical operator precedence is not respected.
|
||||
# binary 'operators' are evaluated in ltr order
|
||||
1 + 1. # 2
|
||||
8 - 4. # 4
|
||||
10 + 2 * 3. # 36
|
||||
|
||||
# Division is always floating division
|
||||
35 / 2 # 17.5.
|
||||
|
||||
# Integer division is non-trivial, you may use floor
|
||||
(35 / 2) floor # 17.
|
||||
|
||||
# Booleans are primitives
|
||||
True.
|
||||
False.
|
||||
|
||||
# Boolean messages
|
||||
True not. # False
|
||||
False not. # True
|
||||
1 = 1. # True
|
||||
1 !=: 1. # False
|
||||
1 < 10. # True
|
||||
|
||||
# Here, `not` is a unary message to the object `Boolean`
|
||||
# Messages are comparable to instance method calls
|
||||
# And they have three different forms:
|
||||
# 1. Unary messages: Length > 1, and they take no arguments:
|
||||
False not.
|
||||
# 2. Binary Messages: Length = 1, and they take a single argument:
|
||||
False & True.
|
||||
# 3. Keyword messages: must have at least one ':', they take as many arguments
|
||||
# as they have `:` s
|
||||
False either: 1 or: 2. # 2
|
||||
|
||||
# Strings
|
||||
'This is a string'.
|
||||
'There are no character types exposed to the user'.
|
||||
# "You cannot use double quotes for strings" <- Error
|
||||
|
||||
# Strins can be summed
|
||||
'Hello, ' + 'World!'. # 'Hello, World!'
|
||||
|
||||
# Strings allow access to their characters
|
||||
'This is a beautiful string' at: 0. # 'T'
|
||||
|
||||
###########################################
|
||||
## intermission: Basic Assignment
|
||||
###########################################
|
||||
|
||||
# You may assign values to the current scope:
|
||||
var name is value. # assignes `value` into `name`
|
||||
|
||||
# You may also assign values into the current object's namespace
|
||||
my name is value. # assigns `value` into the current object's `name` property
|
||||
|
||||
# Please note that these names are checked at compile (read parse if in interpreted mode) time
|
||||
# but you may treat them as dynamic assignments anyway
|
||||
|
||||
###########################################
|
||||
## 2. Lists(Arrays?) and Tuples
|
||||
###########################################
|
||||
|
||||
# Arrays are allowed to have multiple types
|
||||
Array new < 1 ; 2 ; 'string' ; Nil. # Array new < 1 ; 2 ; 'string' ; Nil
|
||||
|
||||
# Tuples act like arrays, but are immutable.
|
||||
# Any shenanigans degrade them to arrays, however
|
||||
[1, 2, 'string']. # [1, 2, 'string']
|
||||
|
||||
# They can interoperate with arrays
|
||||
[1, 'string'] + (Array new < 'wat'). # Array new < 1 ; 'string' ; 'wat'
|
||||
|
||||
# Indexing into them
|
||||
[1, 2, 3] at: 1. # 2
|
||||
|
||||
# Some array operations
|
||||
var arr is Array new < 1 ; 2 ; 3.
|
||||
|
||||
arr head. # 1
|
||||
arr tail. # Array new < 2 ; 3.
|
||||
arr init. # Array new < 1 ; 2.
|
||||
arr last. # 3
|
||||
arr push: 4. # Array new < 1 ; 2 ; 3 ; 4.
|
||||
arr pop. # 4
|
||||
arr pop: 1. # 2, `arr` is rebound to Array new < 1 ; 3.
|
||||
|
||||
# List comprehensions
|
||||
[x * 2 + y,, arr, arr + [4, 5],, x > 1]. # Array ← 7 ; 9 ; 10 ; 11
|
||||
# fresh variable names are bound as they are encountered,
|
||||
# so `x` is bound to the values in `arr`
|
||||
# and `y` is bound to the values in `arr + [4, 5]`
|
||||
#
|
||||
# The general format is: [expr,, bindings*,, predicates*]
|
||||
|
||||
|
||||
####################################
|
||||
## 3. Functions
|
||||
####################################
|
||||
|
||||
# A simple function that takes two variables
|
||||
var add is {:a:b ^a + b.}.
|
||||
|
||||
# this function will resolve all its names except the formal arguments
|
||||
# in the context it is called in.
|
||||
|
||||
# Using the function
|
||||
add applyTo: 3 and: 5. # 8
|
||||
add applyAll: [3, 5]. # 8
|
||||
|
||||
# Also a (customizable -- more on this later) pseudo-operator allows for a shorthand
|
||||
# of function calls
|
||||
# By default it is REF[args]
|
||||
|
||||
add[3, 5]. # 8
|
||||
|
||||
# To customize this behaviour, you may simply use a compiler pragma:
|
||||
#:callShorthand ()
|
||||
|
||||
# And then you may use the specified operator.
|
||||
# Note that the allowed 'operator' can only be made of any of these: []{}()
|
||||
# And you may mix-and-match (why would anyone do that?)
|
||||
|
||||
add(3, 5). # 8
|
||||
|
||||
# You may also use functions as operators in the following way:
|
||||
|
||||
3 `add` 5. # 8
|
||||
# This call binds as such: add[(3), 5]
|
||||
# because the default fixity is left, and the default precedance is 1
|
||||
|
||||
# You may change the precedence/fixity of this operator with a pragma
|
||||
#:declare infixr 1 add
|
||||
|
||||
3 `add` 5. # 8
|
||||
# now this binds as such: add[3, (5)].
|
||||
|
||||
# There is another form of functions too
|
||||
# So far, the functions were resolved in a dynamic fashion
|
||||
# But a lexically scoped block is also possible
|
||||
var sillyAdd is {\:x:y add[x,y].}.
|
||||
|
||||
# In these blocks, you are not allowed to declare new variables
|
||||
# Except with the use of Object::'letEqual:in:`
|
||||
# And the last expression is implicitly returned.
|
||||
|
||||
# You may also use a shorthand for lambda expressions
|
||||
var mul is \:x:y x * y.
|
||||
|
||||
# These capture the named bindings that are not present in their
|
||||
# formal parameters, and retain them. (by ref)
|
||||
|
||||
###########################################
|
||||
## 5. Control Flow
|
||||
###########################################
|
||||
|
||||
# inline conditional-expressions
|
||||
var citron is 1 = 1 either: 'awesome' or: 'awful'. # citron is 'awesome'
|
||||
|
||||
# multiple lines is fine too
|
||||
var citron is 1 = 1
|
||||
either: 'awesome'
|
||||
or: 'awful'.
|
||||
|
||||
# looping
|
||||
10 times: {:x
|
||||
Pen writeln: x.
|
||||
}. # 10. -- side effect: 10 lines in stdout, with numbers 0 through 9 in them
|
||||
|
||||
# Citron properly supports tail-call recursion in lexically scoped blocks
|
||||
# So use those to your heart's desire
|
||||
|
||||
# mapping most data structures is as simple as `fmap:`
|
||||
[1, 2, 3, 4] fmap: \:x x + 1. # [2, 3, 4, 5]
|
||||
|
||||
# You can use `foldl:accumulator:` to fold a list/tuple
|
||||
[1, 2, 3, 4] foldl: (\:acc:x acc * 2 + x) accumulator: 4. # 90
|
||||
|
||||
# That expression is the same as
|
||||
(2 * (2 * (2 * (2 * 4 + 1) + 2) + 3) + 4)
|
||||
|
||||
###################################
|
||||
## 6. IO
|
||||
###################################
|
||||
|
||||
# IO is quite simple
|
||||
# With `Pen` being used for console output
|
||||
# and Program::'input' and Program::'waitForInput' being used for console input
|
||||
|
||||
Pen writeln: 'Hello, ocean!' # prints 'Hello, ocean!\n' to the terminal
|
||||
|
||||
Pen writeln: Program waitForInput. # reads a line and prints it back
|
||||
```
|
@ -150,7 +150,7 @@ x ; => 1
|
||||
|
||||
; You can also use this shorthand to create functions:
|
||||
(def hello2 #(str "Hello " %1))
|
||||
(hello2 "Fanny") ; => "Hello Fanny"
|
||||
(hello2 "Julie") ; => "Hello Julie"
|
||||
|
||||
; You can have multi-variadic functions, too
|
||||
(defn hello3
|
||||
|
@ -4,82 +4,91 @@ language: "Common Lisp"
|
||||
filename: commonlisp.lisp
|
||||
contributors:
|
||||
- ["Paul Nathan", "https://github.com/pnathan"]
|
||||
- ["Rommel Martinez", "https://ebzzry.io"]
|
||||
---
|
||||
|
||||
ANSI Common Lisp is a general purpose, multi-paradigm programming
|
||||
language suited for a wide variety of industry applications. It is
|
||||
frequently referred to as a programmable programming language.
|
||||
Common Lisp is a general-purpose, multi-paradigm programming language suited for a wide variety of
|
||||
industry applications. It is frequently referred to as a programmable programming language.
|
||||
|
||||
The classic starting point is [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/)
|
||||
|
||||
Another popular and recent book is
|
||||
[Land of Lisp](http://landoflisp.com/).
|
||||
The classic starting point is [Practical Common Lisp](http://www.gigamonkeys.com/book/). Another
|
||||
popular and recent book is [Land of Lisp](http://landoflisp.com/). A new book about best practices,
|
||||
[Common Lisp Recipes](http://weitz.de/cl-recipes/), was recently published.
|
||||
|
||||
|
||||
|
||||
```common_lisp
|
||||
```lisp
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 0. Syntax
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
;;; General form.
|
||||
;;; General form
|
||||
|
||||
;; Lisp has two fundamental pieces of syntax: the ATOM and the
|
||||
;; S-expression. Typically, grouped S-expressions are called `forms`.
|
||||
;;; CL has two fundamental pieces of syntax: ATOM and S-EXPRESSION.
|
||||
;;; Typically, grouped S-expressions are called `forms`.
|
||||
|
||||
10 ; an atom; it evaluates to itself
|
||||
|
||||
:THING ;Another atom; evaluating to the symbol :thing.
|
||||
|
||||
t ; another atom, denoting true.
|
||||
|
||||
(+ 1 2 3 4) ; an s-expression
|
||||
|
||||
'(4 :foo t) ;another one
|
||||
10 ; an atom; it evaluates to itself
|
||||
:thing ; another atom; evaluating to the symbol :thing
|
||||
t ; another atom, denoting true
|
||||
(+ 1 2 3 4) ; an s-expression
|
||||
'(4 :foo t) ; another s-expression
|
||||
|
||||
|
||||
;;; Comments
|
||||
|
||||
;; Single line comments start with a semicolon; use two for normal
|
||||
;; comments, three for section comments, and four for file-level
|
||||
;; comments.
|
||||
;;; Single-line comments start with a semicolon; use four for file-level
|
||||
;;; comments, three for section descriptions, two inside definitions, and one
|
||||
;;; for single lines. For example,
|
||||
|
||||
#| Block comments
|
||||
can span multiple lines and...
|
||||
;;;; life.lisp
|
||||
|
||||
;;; Foo bar baz, because quu quux. Optimized for maximum krakaboom and umph.
|
||||
;;; Needed by the function LINULUKO.
|
||||
|
||||
(defun meaning (life)
|
||||
"Return the computed meaning of LIFE"
|
||||
(let ((meh "abc"))
|
||||
;; Invoke krakaboom
|
||||
(loop :for x :across meh
|
||||
:collect x))) ; store values into x, then return it
|
||||
|
||||
;;; Block comments, on the other hand, allow for free-form comments. They are
|
||||
;;; delimited with #| and |#
|
||||
|
||||
#| This is a block comment which
|
||||
can span multiple lines and
|
||||
#|
|
||||
they can be nested!
|
||||
|#
|
||||
|#
|
||||
|
||||
;;; Environment.
|
||||
|
||||
;; A variety of implementations exist; most are
|
||||
;; standard-conformant. CLISP is a good starting one.
|
||||
;;; Environment
|
||||
|
||||
;; Libraries are managed through Quicklisp.org's Quicklisp system.
|
||||
;;; A variety of implementations exist; most are standards-conformant. SBCL
|
||||
;;; is a good starting point. Third party libraries can be easily installed with
|
||||
;;; Quicklisp
|
||||
|
||||
;; Common Lisp is usually developed with a text editor and a REPL
|
||||
;; (Read Evaluate Print Loop) running at the same time. The REPL
|
||||
;; allows for interactive exploration of the program as it is "live"
|
||||
;; in the system.
|
||||
;;; CL is usually developed with a text editor and a Real Eval Print
|
||||
;;; Loop (REPL) running at the same time. The REPL allows for interactive
|
||||
;;; exploration of the program while it is running "live".
|
||||
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;; 1. Primitive Datatypes and Operators
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 1. Primitive datatypes and operators
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
;;; Symbols
|
||||
|
||||
'foo ; => FOO Notice that the symbol is upper-cased automatically.
|
||||
|
||||
;; Intern manually creates a symbol from a string.
|
||||
;;; INTERN manually creates a symbol from a string.
|
||||
|
||||
(intern "AAAA") ; => AAAA
|
||||
|
||||
(intern "aaa") ; => |aaa|
|
||||
(intern "AAAA") ; => AAAA
|
||||
(intern "aaa") ; => |aaa|
|
||||
|
||||
;;; Numbers
|
||||
|
||||
9999999999999999999999 ; integers
|
||||
#b111 ; binary => 7
|
||||
#o111 ; octal => 73
|
||||
@ -89,313 +98,363 @@ t ; another atom, denoting true.
|
||||
1/2 ; ratios
|
||||
#C(1 2) ; complex numbers
|
||||
|
||||
;;; Function application are written as (f x y z ...) where f is a function and
|
||||
;;; x, y, z, ... are the arguments.
|
||||
|
||||
;; Function application is written (f x y z ...)
|
||||
;; where f is a function and x, y, z, ... are operands
|
||||
;; If you want to create a literal list of data, use ' to stop it from
|
||||
;; being evaluated - literally, "quote" the data.
|
||||
'(+ 1 2) ; => (+ 1 2)
|
||||
;; You can also call a function manually:
|
||||
(funcall #'+ 1 2 3) ; => 6
|
||||
;; Some arithmetic operations
|
||||
(+ 1 1) ; => 2
|
||||
(- 8 1) ; => 7
|
||||
(* 10 2) ; => 20
|
||||
(expt 2 3) ; => 8
|
||||
(mod 5 2) ; => 1
|
||||
(/ 35 5) ; => 7
|
||||
(/ 1 3) ; => 1/3
|
||||
(+ #C(1 2) #C(6 -4)) ; => #C(7 -2)
|
||||
(+ 1 2) ; => 3
|
||||
|
||||
;;; Booleans
|
||||
t ; for true (any not-nil value is true)
|
||||
nil ; for false - and the empty list
|
||||
(not nil) ; => t
|
||||
(and 0 t) ; => t
|
||||
(or 0 nil) ; => 0
|
||||
;;; If you want to create literal data, use QUOTE to prevent it from being
|
||||
;;; evaluated
|
||||
|
||||
;;; Characters
|
||||
#\A ; => #\A
|
||||
#\λ ; => #\GREEK_SMALL_LETTER_LAMDA
|
||||
#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA
|
||||
(quote (+ 1 2)) ; => (+ 1 2)
|
||||
(quote a) ; => A
|
||||
|
||||
;;; The shorthand for QUOTE is '
|
||||
|
||||
'(+ 1 2) ; => (+ 1 2)
|
||||
'a ; => A
|
||||
|
||||
;;; Basic arithmetic operations
|
||||
|
||||
(+ 1 1) ; => 2
|
||||
(- 8 1) ; => 7
|
||||
(* 10 2) ; => 20
|
||||
(expt 2 3) ; => 8
|
||||
(mod 5 2) ; => 1
|
||||
(/ 35 5) ; => 7
|
||||
(/ 1 3) ; => 1/3
|
||||
(+ #C(1 2) #C(6 -4)) ; => #C(7 -2)
|
||||
|
||||
;;; Booleans
|
||||
|
||||
t ; true; any non-NIL value is true
|
||||
nil ; false; also, the empty list: ()
|
||||
(not nil) ; => T
|
||||
(and 0 t) ; => T
|
||||
(or 0 nil) ; => 0
|
||||
|
||||
;;; Characters
|
||||
|
||||
#\A ; => #\A
|
||||
#\λ ; => #\GREEK_SMALL_LETTER_LAMDA
|
||||
#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA
|
||||
|
||||
;;; Strings are fixed-length arrays of characters
|
||||
|
||||
;;; Strings are fixed-length arrays of characters.
|
||||
"Hello, world!"
|
||||
"Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character
|
||||
|
||||
;; Strings can be concatenated too!
|
||||
(concatenate 'string "Hello " "world!") ; => "Hello world!"
|
||||
;;; Strings can be concatenated
|
||||
|
||||
(concatenate 'string "Hello, " "world!") ; => "Hello, world!"
|
||||
|
||||
;;; A string can be treated like a sequence of characters
|
||||
|
||||
;; A string can be treated like a sequence of characters
|
||||
(elt "Apple" 0) ; => #\A
|
||||
|
||||
;; format can be used to format strings:
|
||||
(format nil "~a can be ~a" "strings" "formatted")
|
||||
;;; FORMAT is used to create formatted output, which ranges from simple string
|
||||
;;; interpolation to loops and conditionals. The first argument to FORMAT
|
||||
;;; determines where will the formatted string go. If it is NIL, FORMAT
|
||||
;;; simply returns the formatted string as a value; if it is T, FORMAT outputs
|
||||
;;; to the standard output, usually the screen, then it returns NIL.
|
||||
|
||||
;; Printing is pretty easy; ~% is the format specifier for newline.
|
||||
(format t "Common Lisp is groovy. Dude.~%")
|
||||
(format nil "~A, ~A!" "Hello" "world") ; => "Hello, world!"
|
||||
(format t "~A, ~A!" "Hello" "world") ; => NIL
|
||||
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 2. Variables
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; You can create a global (dynamically scoped) using defparameter
|
||||
;; a variable name can use any character except: ()",'`;#|\
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 2. Variables
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
;; Dynamically scoped variables should have earmuffs in their name!
|
||||
;;; You can create a global (dynamically scoped) variable using DEFVAR and
|
||||
;;; DEFPARAMETER. The variable name can use any character except: ()",'`;#|\
|
||||
|
||||
;;; The difference between DEFVAR and DEFPARAMETER is that re-evaluating a
|
||||
;;; DEFVAR expression doesn't change the value of the variable. DEFPARAMETER,
|
||||
;;; on the other hand, does.
|
||||
|
||||
;;; By convention, dynamically scoped variables have earmuffs in their name.
|
||||
|
||||
(defparameter *some-var* 5)
|
||||
*some-var* ; => 5
|
||||
|
||||
;; You can also use unicode characters.
|
||||
;;; You can also use unicode characters.
|
||||
(defparameter *AΛB* nil)
|
||||
|
||||
;;; Accessing a previously unbound variable results in an UNBOUND-VARIABLE
|
||||
;;; error, however it is defined behavior. Don't do it.
|
||||
|
||||
;; Accessing a previously unbound variable is an
|
||||
;; undefined behavior (but possible). Don't do it.
|
||||
;;; You can create local bindings with LET. In the following snippet, `me` is
|
||||
;;; bound to "dance with you" only within the (let ...). LET always returns
|
||||
;;; the value of the last `form` in the LET form.
|
||||
|
||||
(let ((me "dance with you")) me) ; => "dance with you"
|
||||
|
||||
|
||||
;; Local binding: `me` is bound to "dance with you" only within the
|
||||
;; (let ...). Let always returns the value of the last `form` in the
|
||||
;; let form.
|
||||
;;;-----------------------------------------------------------------------------;
|
||||
;;; 3. Structs and collections
|
||||
;;;-----------------------------------------------------------------------------;
|
||||
|
||||
(let ((me "dance with you"))
|
||||
me)
|
||||
;; => "dance with you"
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 3. Structs and Collections
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;; Structs
|
||||
|
||||
;; Structs
|
||||
(defstruct dog name breed age)
|
||||
(defparameter *rover*
|
||||
(make-dog :name "rover"
|
||||
:breed "collie"
|
||||
:age 5))
|
||||
*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5)
|
||||
|
||||
(dog-p *rover*) ; => true #| -p signifies "predicate". It's used to
|
||||
check if *rover* is an instance of dog. |#
|
||||
*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5)
|
||||
(dog-p *rover*) ; => T
|
||||
(dog-name *rover*) ; => "rover"
|
||||
|
||||
;; Dog-p, make-dog, and dog-name are all created by defstruct!
|
||||
;;; DOG-P, MAKE-DOG, and DOG-NAME are all automatically created by DEFSTRUCT
|
||||
|
||||
|
||||
;;; Pairs
|
||||
;; `cons' constructs pairs, `car' and `cdr' extract the first
|
||||
;; and second elements
|
||||
(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB)
|
||||
(car (cons 'SUBJECT 'VERB)) ; => SUBJECT
|
||||
(cdr (cons 'SUBJECT 'VERB)) ; => VERB
|
||||
|
||||
;;; CONS constructs pairs. CAR and CDR return the head and tail of a CONS-pair.
|
||||
|
||||
(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB)
|
||||
(car (cons 'SUBJECT 'VERB)) ; => SUBJECT
|
||||
(cdr (cons 'SUBJECT 'VERB)) ; => VERB
|
||||
|
||||
|
||||
;;; Lists
|
||||
|
||||
;; Lists are linked-list data structures, made of `cons' pairs and end
|
||||
;; with a `nil' (or '()) to mark the end of the list
|
||||
(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3)
|
||||
;; `list' is a convenience variadic constructor for lists
|
||||
(list 1 2 3) ; => '(1 2 3)
|
||||
;; and a quote can also be used for a literal list value
|
||||
'(1 2 3) ; => '(1 2 3)
|
||||
;;; Lists are linked-list data structures, made of CONS pairs and end with a
|
||||
;;; NIL (or '()) to mark the end of the list
|
||||
|
||||
;; Can still use `cons' to add an item to the beginning of a list
|
||||
(cons 4 '(1 2 3)) ; => '(4 1 2 3)
|
||||
(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3)
|
||||
|
||||
;; Use `append' to - surprisingly - append lists together
|
||||
(append '(1 2) '(3 4)) ; => '(1 2 3 4)
|
||||
;;; LIST is a convenience variadic constructor for lists
|
||||
|
||||
;; Or use concatenate -
|
||||
(list 1 2 3) ; => '(1 2 3)
|
||||
|
||||
(concatenate 'list '(1 2) '(3 4))
|
||||
;;; When the first argument to CONS is an atom and the second argument is a
|
||||
;;; list, CONS returns a new CONS-pair with the first argument as the first
|
||||
;;; item and the second argument as the rest of the CONS-pair
|
||||
|
||||
(cons 4 '(1 2 3)) ; => '(4 1 2 3)
|
||||
|
||||
;;; Use APPEND to join lists
|
||||
|
||||
(append '(1 2) '(3 4)) ; => '(1 2 3 4)
|
||||
|
||||
;;; Or CONCATENATE
|
||||
|
||||
(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4)
|
||||
|
||||
;;; Lists are a very central type, so there is a wide variety of functionality for
|
||||
;;; them, a few examples:
|
||||
|
||||
;; Lists are a very central type, so there is a wide variety of functionality for
|
||||
;; them, a few examples:
|
||||
(mapcar #'1+ '(1 2 3)) ; => '(2 3 4)
|
||||
(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33)
|
||||
(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4)
|
||||
(every #'evenp '(1 2 3 4)) ; => nil
|
||||
(every #'evenp '(1 2 3 4)) ; => NIL
|
||||
(some #'oddp '(1 2 3 4)) ; => T
|
||||
(butlast '(subject verb object)) ; => (SUBJECT VERB)
|
||||
|
||||
|
||||
;;; Vectors
|
||||
|
||||
;; Vector's literals are fixed-length arrays
|
||||
;;; Vector's literals are fixed-length arrays
|
||||
|
||||
#(1 2 3) ; => #(1 2 3)
|
||||
|
||||
;; Use concatenate to add vectors together
|
||||
;;; Use CONCATENATE to add vectors together
|
||||
|
||||
(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6)
|
||||
|
||||
|
||||
;;; Arrays
|
||||
|
||||
;; Both vectors and strings are special-cases of arrays.
|
||||
;;; Both vectors and strings are special-cases of arrays.
|
||||
|
||||
;; 2D arrays
|
||||
;;; 2D arrays
|
||||
|
||||
(make-array (list 2 2))
|
||||
(make-array (list 2 2)) ; => #2A((0 0) (0 0))
|
||||
(make-array '(2 2)) ; => #2A((0 0) (0 0))
|
||||
(make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0)))
|
||||
|
||||
;; (make-array '(2 2)) works as well.
|
||||
;;; Caution: the default initial values of MAKE-ARRAY are implementation-defined.
|
||||
;;; To explicitly specify them:
|
||||
|
||||
; => #2A((0 0) (0 0))
|
||||
(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET)
|
||||
|
||||
(make-array (list 2 2 2))
|
||||
;;; To access the element at 1, 1, 1:
|
||||
|
||||
; => #3A(((0 0) (0 0)) ((0 0) (0 0)))
|
||||
|
||||
;; Caution- the default initial values are
|
||||
;; implementation-defined. Here's how to define them:
|
||||
|
||||
(make-array '(2) :initial-element 'unset)
|
||||
|
||||
; => #(UNSET UNSET)
|
||||
|
||||
;; And, to access the element at 1,1,1 -
|
||||
(aref (make-array (list 2 2 2)) 1 1 1)
|
||||
|
||||
; => 0
|
||||
(aref (make-array (list 2 2 2)) 1 1 1) ; => 0
|
||||
;;; This value is implementation-defined:
|
||||
;;; NIL on ECL, 0 on SBCL and CCL.
|
||||
|
||||
;;; Adjustable vectors
|
||||
|
||||
;; Adjustable vectors have the same printed representation
|
||||
;; as fixed-length vector's literals.
|
||||
;;; Adjustable vectors have the same printed representation as
|
||||
;;; fixed-length vector's literals.
|
||||
|
||||
(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
|
||||
:adjustable t :fill-pointer t))
|
||||
|
||||
:adjustable t :fill-pointer t))
|
||||
*adjvec* ; => #(1 2 3)
|
||||
|
||||
;; Adding new element:
|
||||
(vector-push-extend 4 *adjvec*) ; => 3
|
||||
;;; Adding new elements
|
||||
|
||||
*adjvec* ; => #(1 2 3 4)
|
||||
(vector-push-extend 4 *adjvec*) ; => 3
|
||||
*adjvec* ; => #(1 2 3 4)
|
||||
|
||||
|
||||
;;; Sets, naively, are just lists:
|
||||
|
||||
;;; Naively, sets are just lists:
|
||||
(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1)
|
||||
(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4
|
||||
(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7)
|
||||
(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4)
|
||||
|
||||
(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1)
|
||||
(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4
|
||||
(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7)
|
||||
(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4)
|
||||
|
||||
;; But you'll want to use a better data structure than a linked list
|
||||
;; for performant work!
|
||||
;;; However, you'll need a better data structure than linked lists when working
|
||||
;;; with larger data sets
|
||||
|
||||
;;; Dictionaries are implemented as hash tables.
|
||||
|
||||
;; Create a hash table
|
||||
;;; Create a hash table
|
||||
|
||||
(defparameter *m* (make-hash-table))
|
||||
|
||||
;; set a value
|
||||
;;; Set value
|
||||
|
||||
(setf (gethash 'a *m*) 1)
|
||||
|
||||
;; Retrieve a value
|
||||
(gethash 'a *m*) ; => 1, t
|
||||
;;; Retrieve value
|
||||
|
||||
;; Detail - Common Lisp has multiple return values possible. gethash
|
||||
;; returns t in the second value if anything was found, and nil if
|
||||
;; not.
|
||||
(gethash 'a *m*) ; => 1, T
|
||||
|
||||
;; Retrieving a non-present value returns nil
|
||||
(gethash 'd *m*) ;=> nil, nil
|
||||
;;; CL expressions have the ability to return multiple values.
|
||||
|
||||
(values 1 2) ; => 1, 2
|
||||
|
||||
;;; which can be bound with MULTIPLE-VALUE-BIND
|
||||
|
||||
(multiple-value-bind (x y)
|
||||
(values 1 2)
|
||||
(list y x))
|
||||
|
||||
; => '(2 1)
|
||||
|
||||
;;; GETHASH is an example of a function that returns multiple values. The first
|
||||
;;; value it return is the value of the key in the hash table; if the key is
|
||||
;;; not found it returns NIL.
|
||||
|
||||
;;; The second value determines if that key is indeed present in the hash
|
||||
;;; table. If a key is not found in the table it returns NIL. This behavior
|
||||
;;; allows us to check if the value of a key is actually NIL.
|
||||
|
||||
;;; Retrieving a non-present value returns nil
|
||||
|
||||
(gethash 'd *m*) ;=> NIL, NIL
|
||||
|
||||
;;; You can provide a default value for missing keys
|
||||
|
||||
;; You can provide a default value for missing keys
|
||||
(gethash 'd *m* :not-found) ; => :NOT-FOUND
|
||||
|
||||
;; Let's handle the multiple return values here in code.
|
||||
;;; Let's handle the multiple return values here in code.
|
||||
|
||||
(multiple-value-bind
|
||||
(a b)
|
||||
(multiple-value-bind (a b)
|
||||
(gethash 'd *m*)
|
||||
(list a b))
|
||||
; => (NIL NIL)
|
||||
|
||||
(multiple-value-bind
|
||||
(a b)
|
||||
(multiple-value-bind (a b)
|
||||
(gethash 'a *m*)
|
||||
(list a b))
|
||||
; => (1 T)
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 3. Functions
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Use `lambda' to create anonymous functions.
|
||||
;; A function always returns the value of its last expression.
|
||||
;; The exact printable representation of a function will vary...
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 3. Functions
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
;;; Use LAMBDA to create anonymous functions. Functions always returns the
|
||||
;;; value of the last expression. The exact printable representation of a
|
||||
;;; function varies between implementations.
|
||||
|
||||
(lambda () "Hello World") ; => #<FUNCTION (LAMBDA ()) {1004E7818B}>
|
||||
|
||||
;; Use funcall to call lambda functions
|
||||
(funcall (lambda () "Hello World")) ; => "Hello World"
|
||||
;;; Use FUNCALL to call anonymous functions
|
||||
|
||||
;; Or Apply
|
||||
(funcall (lambda () "Hello World")) ; => "Hello World"
|
||||
(funcall #'+ 1 2 3) ; => 6
|
||||
|
||||
;;; A call to FUNCALL is also implied when the lambda expression is the CAR of
|
||||
;;; an unquoted list
|
||||
|
||||
((lambda () "Hello World")) ; => "Hello World"
|
||||
((lambda (val) val) "Hello World") ; => "Hello World"
|
||||
|
||||
;;; FUNCALL is used when the arguments are known beforehand. Otherwise, use APPLY
|
||||
|
||||
(apply #'+ '(1 2 3)) ; => 6
|
||||
(apply (lambda () "Hello World") nil) ; => "Hello World"
|
||||
|
||||
;; De-anonymize the function
|
||||
(defun hello-world ()
|
||||
"Hello World")
|
||||
;;; To name a function, use DEFUN
|
||||
|
||||
(defun hello-world () "Hello World")
|
||||
(hello-world) ; => "Hello World"
|
||||
|
||||
;; The () in the above is the list of arguments for the function
|
||||
(defun hello (name)
|
||||
(format nil "Hello, ~a" name))
|
||||
;;; The () in the definition above is the list of arguments
|
||||
|
||||
(defun hello (name) (format nil "Hello, ~A" name))
|
||||
(hello "Steve") ; => "Hello, Steve"
|
||||
|
||||
;; Functions can have optional arguments; they default to nil
|
||||
;;; Functions can have optional arguments; they default to NIL
|
||||
|
||||
(defun hello (name &optional from)
|
||||
(if from
|
||||
(format t "Hello, ~a, from ~a" name from)
|
||||
(format t "Hello, ~a" name)))
|
||||
(if from
|
||||
(format t "Hello, ~A, from ~A" name from)
|
||||
(format t "Hello, ~A" name)))
|
||||
|
||||
(hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas
|
||||
(hello "Jim" "Alpacas") ; => Hello, Jim, from Alpacas
|
||||
|
||||
;;; The default values can also be specified
|
||||
|
||||
;; And the defaults can be set...
|
||||
(defun hello (name &optional (from "The world"))
|
||||
(format t "Hello, ~a, from ~a" name from))
|
||||
(format nil "Hello, ~A, from ~A" name from))
|
||||
|
||||
(hello "Steve")
|
||||
; => Hello, Steve, from The world
|
||||
(hello "Steve") ; => Hello, Steve, from The world
|
||||
(hello "Steve" "the alpacas") ; => Hello, Steve, from the alpacas
|
||||
|
||||
(hello "Steve" "the alpacas")
|
||||
; => Hello, Steve, from the alpacas
|
||||
|
||||
|
||||
;; And of course, keywords are allowed as well... usually more
|
||||
;; flexible than &optional.
|
||||
;;; Functions also have keyword arguments to allow non-positional arguments
|
||||
|
||||
(defun generalized-greeter (name &key (from "the world") (honorific "Mx"))
|
||||
(format t "Hello, ~a ~a, from ~a" honorific name from))
|
||||
(format t "Hello, ~A ~A, from ~A" honorific name from))
|
||||
|
||||
(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world
|
||||
(generalized-greeter "Jim")
|
||||
; => Hello, Mx Jim, from the world
|
||||
|
||||
(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr")
|
||||
; => Hello, Mr Jim, from the alpacas you met last summer
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 4. Equality
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Common Lisp has a sophisticated equality system. A couple are covered here.
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 4. Equality
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
;; for numbers use `='
|
||||
(= 3 3.0) ; => t
|
||||
(= 2 1) ; => nil
|
||||
;;; CL has a sophisticated equality system. Some are covered here.
|
||||
|
||||
;; for object identity (approximately) use `eql`
|
||||
(eql 3 3) ; => t
|
||||
(eql 3 3.0) ; => nil
|
||||
(eql (list 3) (list 3)) ; => nil
|
||||
;;; For numbers, use `='
|
||||
(= 3 3.0) ; => T
|
||||
(= 2 1) ; => NIL
|
||||
|
||||
;; for lists, strings, and bit-vectors use `equal'
|
||||
(equal (list 'a 'b) (list 'a 'b)) ; => t
|
||||
(equal (list 'a 'b) (list 'b 'a)) ; => nil
|
||||
;;; For object identity (approximately) use EQL
|
||||
(eql 3 3) ; => T
|
||||
(eql 3 3.0) ; => NIL
|
||||
(eql (list 3) (list 3)) ; => NIL
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 5. Control Flow
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;; for lists, strings, and bit-vectors use EQUAL
|
||||
(equal (list 'a 'b) (list 'a 'b)) ; => T
|
||||
(equal (list 'a 'b) (list 'b 'a)) ; => NIL
|
||||
|
||||
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 5. Control Flow
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
;;; Conditionals
|
||||
|
||||
@ -404,71 +463,75 @@ nil ; for false - and the empty list
|
||||
"this is false") ; else expression
|
||||
; => "this is true"
|
||||
|
||||
;; In conditionals, all non-nil values are treated as true
|
||||
;;; In conditionals, all non-NIL values are treated as true
|
||||
|
||||
(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO)
|
||||
(if (member 'Groucho '(Harpo Groucho Zeppo))
|
||||
'yep
|
||||
'nope)
|
||||
; => 'YEP
|
||||
|
||||
;; `cond' chains a series of tests to select a result
|
||||
;;; COND chains a series of tests to select a result
|
||||
(cond ((> 2 2) (error "wrong!"))
|
||||
((< 2 2) (error "wrong again!"))
|
||||
(t 'ok)) ; => 'OK
|
||||
|
||||
;; Typecase switches on the type of the value
|
||||
;;; TYPECASE switches on the type of the value
|
||||
(typecase 1
|
||||
(string :string)
|
||||
(integer :int))
|
||||
|
||||
; => :int
|
||||
|
||||
|
||||
;;; Looping
|
||||
|
||||
;;; Recursion
|
||||
|
||||
(defun fact (n)
|
||||
(if (< n 2)
|
||||
1
|
||||
(* n (fact(- n 1)))))
|
||||
|
||||
(fact 5) ; => 120
|
||||
|
||||
;;; Iteration
|
||||
|
||||
;; Of course recursion is supported:
|
||||
(defun fact (n)
|
||||
(loop :for result = 1 :then (* result i)
|
||||
:for i :from 2 :to n
|
||||
:finally (return result)))
|
||||
|
||||
(defun walker (n)
|
||||
(if (zerop n)
|
||||
:walked
|
||||
(walker (- n 1))))
|
||||
|
||||
(walker 5) ; => :walked
|
||||
|
||||
;; Most of the time, we use DOLIST or LOOP
|
||||
(fact 5) ; => 120
|
||||
|
||||
(loop :for x :across "abcd" :collect x)
|
||||
; => (#\a #\b #\c #\d)
|
||||
|
||||
(dolist (i '(1 2 3 4))
|
||||
(format t "~a" i))
|
||||
|
||||
(format t "~A" i))
|
||||
; => 1234
|
||||
|
||||
(loop for i from 0 below 10
|
||||
collect i)
|
||||
|
||||
; => (0 1 2 3 4 5 6 7 8 9)
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 6. Mutation
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 6. Mutation
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Use `setf' to assign a new value to an existing variable. This was
|
||||
;; demonstrated earlier in the hash table example.
|
||||
;;; Use SETF to assign a new value to an existing variable. This was
|
||||
;;; demonstrated earlier in the hash table example.
|
||||
|
||||
(let ((variable 10))
|
||||
(setf variable 2))
|
||||
; => 2
|
||||
; => 2
|
||||
|
||||
;;; Good Lisp style is to minimize the use of destructive functions and to avoid
|
||||
;;; mutation when reasonable.
|
||||
|
||||
|
||||
;; Good Lisp style is to minimize destructive functions and to avoid
|
||||
;; mutation when reasonable.
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 7. Classes and objects
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 7. Classes and Objects
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; No more Animal classes, let's have Human-Powered Mechanical
|
||||
;; Conveyances.
|
||||
;;; No more animal classes. Let's have Human-Powered Mechanical
|
||||
;;; Conveyances.
|
||||
|
||||
(defclass human-powered-conveyance ()
|
||||
((velocity
|
||||
@ -479,14 +542,16 @@ nil ; for false - and the empty list
|
||||
:initarg :average-efficiency))
|
||||
(:documentation "A human powered conveyance"))
|
||||
|
||||
;; defclass, followed by name, followed by the superclass list,
|
||||
;; followed by slot list, followed by optional qualities such as
|
||||
;; :documentation.
|
||||
;;; The arguments to DEFCLASS, in order are:
|
||||
;;; 1. class name
|
||||
;;; 2. superclass list
|
||||
;;; 3. slot list
|
||||
;;; 4. optional specifiers
|
||||
|
||||
;; When no superclass list is set, the empty list defaults to the
|
||||
;; standard-object class. This *can* be changed, but not until you
|
||||
;; know what you're doing. Look up the Art of the Metaobject Protocol
|
||||
;; for more information.
|
||||
;;; When no superclass list is set, the empty list defaults to the
|
||||
;;; standard-object class. This *can* be changed, but not until you
|
||||
;;; know what you're doing. Look up the Art of the Metaobject Protocol
|
||||
;;; for more information.
|
||||
|
||||
(defclass bicycle (human-powered-conveyance)
|
||||
((wheel-size
|
||||
@ -500,7 +565,7 @@ nil ; for false - and the empty list
|
||||
(defclass recumbent (bicycle)
|
||||
((chain-type
|
||||
:accessor chain-type
|
||||
:initarg :chain-type)))
|
||||
:initarg :chain-type)))
|
||||
|
||||
(defclass unicycle (human-powered-conveyance) nil)
|
||||
|
||||
@ -509,8 +574,7 @@ nil ; for false - and the empty list
|
||||
:accessor number-of-rowers
|
||||
:initarg :number-of-rowers)))
|
||||
|
||||
|
||||
;; Calling DESCRIBE on the human-powered-conveyance class in the REPL gives:
|
||||
;;; Calling DESCRIBE on the HUMAN-POWERED-CONVEYANCE class in the REPL gives:
|
||||
|
||||
(describe 'human-powered-conveyance)
|
||||
|
||||
@ -532,47 +596,42 @@ nil ; for false - and the empty list
|
||||
; Readers: AVERAGE-EFFICIENCY
|
||||
; Writers: (SETF AVERAGE-EFFICIENCY)
|
||||
|
||||
;; Note the reflective behavior available to you! Common Lisp is
|
||||
;; designed to be an interactive system
|
||||
;;; Note the reflective behavior available. CL was designed to be an
|
||||
;;; interactive system
|
||||
|
||||
;; To define a method, let's find out what our circumference of the
|
||||
;; bike wheel turns out to be using the equation: C = d * pi
|
||||
;;; To define a method, let's find out what our circumference of the
|
||||
;;; bike wheel turns out to be using the equation: C = d * pi
|
||||
|
||||
(defmethod circumference ((object bicycle))
|
||||
(* pi (wheel-size object)))
|
||||
|
||||
;; pi is defined in Lisp already for us!
|
||||
;;; PI is defined as a built-in in CL
|
||||
|
||||
;; Let's suppose we find out that the efficiency value of the number
|
||||
;; of rowers in a canoe is roughly logarithmic. This should probably be set
|
||||
;; in the constructor/initializer.
|
||||
;;; Let's suppose we find out that the efficiency value of the number
|
||||
;;; of rowers in a canoe is roughly logarithmic. This should probably be set
|
||||
;;; in the constructor/initializer.
|
||||
|
||||
;; Here's how to initialize your instance after Common Lisp gets done
|
||||
;; constructing it:
|
||||
;;; To initialize your instance after CL gets done constructing it:
|
||||
|
||||
(defmethod initialize-instance :after ((object canoe) &rest args)
|
||||
(setf (average-efficiency object) (log (1+ (number-of-rowers object)))))
|
||||
|
||||
;; Then to construct an instance and check the average efficiency...
|
||||
;;; Then to construct an instance and check the average efficiency...
|
||||
|
||||
(average-efficiency (make-instance 'canoe :number-of-rowers 15))
|
||||
; => 2.7725887
|
||||
|
||||
|
||||
;;;-----------------------------------------------------------------------------
|
||||
;;; 8. Macros
|
||||
;;;-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 8. Macros
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Macros let you extend the syntax of the language
|
||||
|
||||
;; Common Lisp doesn't come with a WHILE loop- let's add one.
|
||||
;; If we obey our assembler instincts, we wind up with:
|
||||
;;; Macros let you extend the syntax of the language. CL doesn't come
|
||||
;;; with a WHILE loop, however, it's trivial to write one. If we obey our
|
||||
;;; assembler instincts, we wind up with:
|
||||
|
||||
(defmacro while (condition &body body)
|
||||
"While `condition` is true, `body` is executed.
|
||||
|
||||
`condition` is tested prior to each execution of `body`"
|
||||
(let ((block-name (gensym)) (done (gensym)))
|
||||
`(tagbody
|
||||
@ -584,47 +643,47 @@ nil ; for false - and the empty list
|
||||
(go ,block-name)
|
||||
,done)))
|
||||
|
||||
;; Let's look at the high-level version of this:
|
||||
|
||||
;;; Let's look at the high-level version of this:
|
||||
|
||||
(defmacro while (condition &body body)
|
||||
"While `condition` is true, `body` is executed.
|
||||
|
||||
`condition` is tested prior to each execution of `body`"
|
||||
`(loop while ,condition
|
||||
do
|
||||
(progn
|
||||
,@body)))
|
||||
|
||||
;; However, with a modern compiler, this is not required; the LOOP
|
||||
;; form compiles equally well and is easier to read.
|
||||
;;; However, with a modern compiler, this is not required; the LOOP form
|
||||
;;; compiles equally well and is easier to read.
|
||||
|
||||
;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator
|
||||
;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting"
|
||||
;; variables. @ interpolates lists.
|
||||
;;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator
|
||||
;;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting"
|
||||
;;; variables. @ interpolates lists.
|
||||
|
||||
;; Gensym creates a unique symbol guaranteed to not exist elsewhere in
|
||||
;; the system. This is because macros are expanded at compile time and
|
||||
;; variables declared in the macro can collide with variables used in
|
||||
;; regular code.
|
||||
;;; GENSYM creates a unique symbol guaranteed to not exist elsewhere in
|
||||
;;; the system. This is because macros are expanded at compile time and
|
||||
;;; variables declared in the macro can collide with variables used in
|
||||
;;; regular code.
|
||||
|
||||
;; See Practical Common Lisp for more information on macros.
|
||||
;;; See Practical Common Lisp and On Lisp for more information on macros.
|
||||
```
|
||||
|
||||
|
||||
## Further Reading
|
||||
## Further reading
|
||||
|
||||
* [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)
|
||||
- [Practical Common Lisp](http://www.gigamonkeys.com/book/)
|
||||
- [Common Lisp: A Gentle Introduction to Symbolic Computation](https://www.cs.cmu.edu/~dst/LispBook/book.pdf)
|
||||
|
||||
|
||||
## Extra Info
|
||||
## Extra information
|
||||
|
||||
* [CLiki](http://www.cliki.net/)
|
||||
* [common-lisp.net](https://common-lisp.net/)
|
||||
* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl)
|
||||
- [CLiki](http://www.cliki.net/)
|
||||
- [common-lisp.net](https://common-lisp.net/)
|
||||
- [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl)
|
||||
- [Lisp Lang](http://lisp-lang.org/)
|
||||
|
||||
## Credits.
|
||||
|
||||
## Credits
|
||||
|
||||
Lots of thanks to the Scheme people for rolling up a great starting
|
||||
point which could be easily moved to Common Lisp.
|
||||
|
@ -301,7 +301,6 @@ end
|
||||
(1..3).each do |index|
|
||||
puts "Index: #{index}"
|
||||
end
|
||||
# Index: 0
|
||||
# Index: 1
|
||||
# Index: 2
|
||||
# Index: 3
|
||||
|
@ -75,8 +75,8 @@ List.head [] -- Nothing
|
||||
|
||||
-- K získání hodnot z dvojice použijte funkce first a second.
|
||||
-- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".)
|
||||
fst ("elm", 42) -- "elm"
|
||||
snd ("elm", 42) -- 42
|
||||
Tuple.first ("elm", 42) -- "elm"
|
||||
Tuple.second ("elm", 42) -- 42
|
||||
|
||||
-- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol.
|
||||
-- Je to jediná hodnota svého typu, který se také nazývá "Unit".
|
||||
|
@ -9,33 +9,28 @@ lang: cs-cz
|
||||
filename: javascript-cz.js
|
||||
---
|
||||
|
||||
JavaScript byl vytvořen Brendan Eichem v roce 1995 pro Netscape. Byl původně
|
||||
zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk Javy,
|
||||
která byla zamýšlena pro více komplexní webové aplikace, ale jeho úzké propojení
|
||||
s webovými stránkami a vestavěná podpora v prohlížečích způsobila, že se stala
|
||||
více běžná ve webovém frontendu než Java.
|
||||
JavaScript byl vytvořen Brendanem Eichem v roce 1995 pro Netscape. Původně byl
|
||||
zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk
|
||||
Javy, která byla zamýšlena pro komplexnější webové aplikace. Úzké propojení
|
||||
JavaScriptu s webovými stránkami a vestavěná podpora v prohlížečích způsobila,
|
||||
že se stal ve webovém frontendu běžnějším než Java.
|
||||
|
||||
|
||||
JavaScript není omezen pouze na webové prohlížeče, např. projekt Node.js,
|
||||
který zprostředkovává samostatně běžící prostředí V8 JavaScriptového enginu z
|
||||
Google Chrome se stává více a více oblíbený pro serverovou část webových aplikací.
|
||||
|
||||
Zpětná vazba je velmi ceněná. Autora článku můžete kontaktovat (anglicky) na
|
||||
[@adambrenecki](https://twitter.com/adambrenecki), nebo
|
||||
[adam@brenecki.id.au](mailto:adam@brenecki.id.au), nebo mě, jakožto překladatele,
|
||||
na [martinek@ludis.me](mailto:martinek@ludis.me).
|
||||
JavaScript není omezen pouze na webové prohlížeče. Např. projekt Node.js,
|
||||
který zprostředkovává samostatně běžící prostředí V8 JavaScriptového jádra z
|
||||
Google Chrome se stává stále oblíbenější i pro serverovou část webových
|
||||
aplikací.
|
||||
|
||||
```js
|
||||
// Komentáře jsou jako v zayku C. Jednořádkové komentáře začínájí dvojitým lomítkem,
|
||||
// Jednořádkové komentáře začínají dvojitým lomítkem,
|
||||
/* a víceřádkové komentáře začínají lomítkem s hvězdičkou
|
||||
a končí hvězdičkou s lomítkem */
|
||||
|
||||
// Vyrazu můžou být spuštěny pomocí ;
|
||||
// Příkazy mohou být ukončeny středníkem ;
|
||||
delejNeco();
|
||||
|
||||
// ... ale nemusí, středníky jsou automaticky vloženy kdekoliv,
|
||||
// kde končí řádka, kromě pár speciálních případů
|
||||
delejNeco()
|
||||
// ... ale nemusí, protože středníky jsou automaticky vloženy kdekoliv,
|
||||
// kde končí řádka, kromě pár speciálních případů.
|
||||
delejNeco();
|
||||
|
||||
// Protože tyto případy můžou způsobit neočekávané výsledky, budeme
|
||||
// středníky v našem návodu používat.
|
||||
@ -44,12 +39,12 @@ delejNeco()
|
||||
// 1. Čísla, řetězce a operátory
|
||||
|
||||
// JavaScript má jeden číselný typ (čímž je 64-bitový IEEE 754 double).
|
||||
// Double má 52-bit přesnost, což je dostatečně přesné pro ukládání celých čísel
|
||||
// do 9✕10¹⁵.
|
||||
// Double má 52-bitovou přesnost, což je dostatečně přesné pro ukládání celých
|
||||
// čísel až do 9✕10¹⁵.
|
||||
3; // = 3
|
||||
1.5; // = 1.5
|
||||
|
||||
// Základní matematické operace fungují, jak byste očekávali
|
||||
// Základní matematické operace fungují tak, jak byste očekávali
|
||||
1 + 1; // = 2
|
||||
0.1 + 0.2; // = 0.30000000000000004
|
||||
8 - 1; // = 7
|
||||
@ -65,30 +60,30 @@ delejNeco()
|
||||
18.5 % 7; // = 4.5
|
||||
|
||||
// Bitové operace také fungují; když provádíte bitové operace, desetinné číslo
|
||||
// (float) se převede na celé číslo (int) se znaménkem *do* 32 bitů
|
||||
// (float) se převede na celé číslo (int) se znaménkem *až do* 32 bitů
|
||||
1 << 2; // = 4
|
||||
|
||||
// Přednost se vynucuje závorkami.
|
||||
(1 + 3) * 2; // = 8
|
||||
|
||||
// Existují 3 hodnoty mimo obor reálných čísel
|
||||
// Existují 3 hodnoty mimo obor reálných čísel:
|
||||
Infinity; // + nekonečno; výsledek např. 1/0
|
||||
-Infinity; // - nekonečno; výsledek např. -1/0
|
||||
NaN; // výsledek např. 0/0, znamená, že výsledek není číslo ('Not a Number')
|
||||
|
||||
// Také existují hodnoty typu bool
|
||||
// Také existují hodnoty typu boolean.
|
||||
true; // pravda
|
||||
false; // nepravda
|
||||
|
||||
// Řetězce znaků jsou obaleny ' nebo ".
|
||||
// Řetězce znaků jsou obaleny ' nebo ".
|
||||
'abc';
|
||||
"Ahoj světe!";
|
||||
"Hello, world";
|
||||
|
||||
// Negace se tvoří pomocí !
|
||||
// Negace se tvoří pomocí znaku !
|
||||
!true; // = false
|
||||
!false; // = true
|
||||
|
||||
// Rovnost se porovnává ===
|
||||
// Rovnost se porovnává pomocí ===
|
||||
1 === 1; // = true
|
||||
2 === 1; // = false
|
||||
|
||||
@ -103,16 +98,16 @@ false; // nepravda
|
||||
2 >= 2; // = true
|
||||
|
||||
// Řetězce znaků se spojují pomocí +
|
||||
"Ahoj " + "světe!"; // = "Ahoj světe!"
|
||||
"Hello " + "world!"; // = "Hello world!"
|
||||
|
||||
// ... což funguje nejenom s řetězci
|
||||
// ... což funguje nejen s řetězci
|
||||
"1, 2, " + 3; // = "1, 2, 3"
|
||||
"Ahoj " + ["světe", "!"] // = "Ahoj světe,!"
|
||||
"Hello " + ["world", "!"]; // = "Hello world,!"
|
||||
|
||||
// a porovnávají se pomocí < nebo >
|
||||
"a" < "b"; // = true
|
||||
|
||||
// Rovnost s převodem typů se dělá pomocí == ...
|
||||
// Rovnost s převodem typů se dělá za pomoci dvojitého rovnítka...
|
||||
"5" == 5; // = true
|
||||
null == undefined; // = true
|
||||
|
||||
@ -124,24 +119,24 @@ null === undefined; // = false
|
||||
13 + !0; // 14
|
||||
"13" + !0; // '13true'
|
||||
|
||||
// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí charAt`
|
||||
// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí `charAt`
|
||||
"Toto je řetězec".charAt(0); // = 'T'
|
||||
|
||||
// ...nebo použít `substring` k získání podřetězce
|
||||
"Ahoj světe".substring(0, 4); // = "Ahoj"
|
||||
// ...nebo použít `substring` k získání podřetězce.
|
||||
"Hello world".substring(0, 5); // = "Hello"
|
||||
|
||||
// `length` znamená délka a je to vlastnost, takže nepoužívejte ()
|
||||
"Ahoj".length; // = 4
|
||||
// `length` znamená délka a je to vlastnost, takže nepoužívejte ().
|
||||
"Hello".length; // = 5
|
||||
|
||||
// Existují také typy `null` a `undefined`.
|
||||
null; // značí, že žádnou hodnotu
|
||||
undefined; // značí, že hodnota nebyla definovaná (ikdyž
|
||||
null; // obvykle označuje něco záměrně bez hodnoty
|
||||
undefined; // obvykle označuje, že hodnota není momentálně definovaná (ačkoli
|
||||
// `undefined` je hodnota sama o sobě)
|
||||
|
||||
// false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní
|
||||
// vrací pravdu (true)..
|
||||
// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, ikdyž 0 == "0"
|
||||
// vrací pravdu
|
||||
// false, null, undefined, NaN, 0 a "" vrací nepravdu (false). Všechno ostatní
|
||||
// vrací pravdu (true).
|
||||
// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, i když 0 == "0"
|
||||
// vrací pravdu.
|
||||
|
||||
///////////////////////////////////
|
||||
// 2. Proměnné, pole a objekty
|
||||
@ -151,11 +146,11 @@ undefined; // značí, že hodnota nebyla definovaná (ikdyž
|
||||
// znak `=`.
|
||||
var promenna = 5;
|
||||
|
||||
// když vynecháte slůvko 'var' nedostanete chybovou hlášku...
|
||||
// Když vynecháte slůvko 'var', nedostanete chybovou hlášku...
|
||||
jinaPromenna = 10;
|
||||
|
||||
// ...ale vaše proměnná bude vytvořena globálně, bude vytvořena v globálním
|
||||
// oblasti působnosti, ne jenom v lokálním tam, kde jste ji vytvořili
|
||||
// ...ale vaše proměnná bude vytvořena globálně. Bude vytvořena v globální
|
||||
// oblasti působnosti, tedy nejenom v lokální tam, kde jste ji vytvořili.
|
||||
|
||||
// Proměnné vytvořené bez přiřazení obsahují hodnotu undefined.
|
||||
var dalsiPromenna; // = undefined
|
||||
@ -163,114 +158,136 @@ var dalsiPromenna; // = undefined
|
||||
// Pokud chcete vytvořit několik proměnných najednou, můžete je oddělit čárkou
|
||||
var someFourthVar = 2, someFifthVar = 4;
|
||||
|
||||
// Existuje kratší forma pro matematické operace na proměnné
|
||||
// Existuje kratší forma pro matematické operace nad proměnnými
|
||||
promenna += 5; // se provede stejně jako promenna = promenna + 5;
|
||||
// promenna je ted 10
|
||||
// promenna je teď 10
|
||||
promenna *= 10; // teď je promenna rovna 100
|
||||
|
||||
// a tohle je způsob, jak přičítat a odečítat 1
|
||||
promenna++; // teď je promenna 101
|
||||
promenna--; // zpět na 100
|
||||
|
||||
// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu
|
||||
var mojePole = ["Ahoj", 45, true];
|
||||
// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu.
|
||||
var myArray = ["Ahoj", 45, true];
|
||||
|
||||
// Jednotlivé hodnoty jsou přístupné přes hranaté závorky.
|
||||
// Členové pole se začínají počítat na nule.
|
||||
myArray[1]; // = 45
|
||||
|
||||
// Pole je proměnlivé délky a členové se můžou měnit
|
||||
myArray.push("Světe");
|
||||
// Pole je proměnlivé délky a členové se můžou měnit.
|
||||
myArray.push("World");
|
||||
myArray.length; // = 4
|
||||
|
||||
// Přidání/změna na specifickém indexu
|
||||
myArray[3] = "Hello";
|
||||
|
||||
// JavaScriptové objekty jsou stejné jako asociativní pole v jinných programovacích
|
||||
// jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota.
|
||||
var mujObjekt = {klic1: "Ahoj", klic2: "světe"};
|
||||
// Přidání nebo odebrání člena ze začátku nebo konce pole
|
||||
myArray.unshift(3); // Přidej jako první člen
|
||||
someVar = myArray.shift(); // Odstraň prvního člena a vrať jeho hodnotu
|
||||
myArray.push(3); // Přidej jako poslední člen
|
||||
someVar = myArray.pop(); // Odstraň posledního člena a vrať jeho hodnotu
|
||||
|
||||
// Klíče jsou řetězce, ale nejsou povinné uvozovky, pokud jsou validní
|
||||
// JavaScriptové identifikátory. Hodnoty můžou být jakéhokoliv typu-
|
||||
// Spoj všechny členy pole středníkem
|
||||
var myArray0 = [32,false,"js",12,56,90];
|
||||
myArray0.join(";") // = "32;false;js;12;56;90"
|
||||
|
||||
// Vrať část pole s elementy od pozice 1 (včetně) do pozice 4 (nepočítaje)
|
||||
myArray0.slice(1,4); // = [false,"js",12]
|
||||
|
||||
// Odstraň čtyři členy od pozice 2, vlož následující
|
||||
// "hi","wr" and "ld"; vrať odstraněné členy
|
||||
myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90]
|
||||
// myArray0 === [32,false,"hi","wr","ld"]
|
||||
|
||||
// JavaScriptové objekty jsou stejné jako asociativní pole v jiných programovacích
|
||||
// jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota.
|
||||
var mujObjekt = {klic1: "Hello", klic2: "World"};
|
||||
|
||||
// Klíče jsou řetězce, ale nemusí mít povinné uvozovky, pokud jsou validními
|
||||
// JavaScriptovými identifikátory. Hodnoty můžou být jakéhokoliv typu.
|
||||
var mujObjekt = {klic: "mojeHodnota", "muj jiny klic": 4};
|
||||
|
||||
// K hodnotám můžeme přistupovat opět pomocí hranatých závorek
|
||||
myObj["muj jiny klic"]; // = 4
|
||||
mujObjekt["muj jiny klic"]; // = 4
|
||||
|
||||
// ... nebo pokud je klíč platným identifikátorem, můžeme přistupovat k
|
||||
// hodnotám i přes tečku
|
||||
mujObjekt.klic; // = "mojeHodnota"
|
||||
|
||||
// Objekty jsou měnitelné, můžeme upravit hodnoty, nebo přidat nové klíče.
|
||||
myObj.mujDalsiKlic = true;
|
||||
mujObjekt.mujDalsiKlic = true;
|
||||
|
||||
// Pokud se snažíte přistoupit ke klíči, který není nastaven, dostanete undefined
|
||||
myObj.dalsiKlic; // = undefined
|
||||
// Pokud se snažíte přistoupit ke klíči, který neexistuje, dostanete undefined.
|
||||
mujObjekt.dalsiKlic; // = undefined
|
||||
|
||||
///////////////////////////////////
|
||||
// 3. Řízení toku programu
|
||||
|
||||
// Syntaxe pro tuto sekci je prakticky stejná jako pro Javu
|
||||
|
||||
// `if` (když) funguje, jak byste čekali.
|
||||
// Funkce `if` funguje, jak byste čekali.
|
||||
var pocet = 1;
|
||||
if (pocet == 3){
|
||||
// provede, když se pocet rovná 3
|
||||
} else if (pocet == 4){
|
||||
// provede, když se pocet rovná 4
|
||||
} else {
|
||||
// provede, když je pocet cokoliv jinného
|
||||
// provede, když je pocet cokoliv jiného
|
||||
}
|
||||
|
||||
// Stejně tak cyklus while
|
||||
// Stejně tak cyklus `while`.
|
||||
while (true){
|
||||
// nekonečný cyklus
|
||||
// nekonečný cyklus!
|
||||
}
|
||||
|
||||
// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou
|
||||
// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou.
|
||||
var vstup;
|
||||
do {
|
||||
vstup = nactiVstup();
|
||||
} while (!jeValidni(vstup))
|
||||
|
||||
// Cyklus for je stejný jako v Javě nebo jazyku C
|
||||
// Cyklus `for` je stejný jako v Javě nebo jazyku C:
|
||||
// inicializace; podmínka pro pokračování; iterace.
|
||||
for (var i = 0; i < 3; i++){
|
||||
// provede třikrát
|
||||
for (var i = 0; i < 5; i++){
|
||||
// provede se pětkrát
|
||||
}
|
||||
|
||||
// Cyklus For-in iteruje přes každo vlastnost prototypu
|
||||
// Opuštění cyklu s návěštím je podobné jako v Javě
|
||||
outer:
|
||||
for (var i = 0; i < 10; i++) {
|
||||
for (var j = 0; j < 10; j++) {
|
||||
if (i == 5 && j ==5) {
|
||||
break outer;
|
||||
// opustí vnější (outer) cyklus místo pouze vnitřního (inner) cyklu
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cyklus For-in iteruje přes každou vlastnost prototypu
|
||||
var popis = "";
|
||||
var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18};
|
||||
for (var x in osoba){
|
||||
popis += osoba[x] + " ";
|
||||
}
|
||||
} // popis = 'Paul Ken 18 '
|
||||
|
||||
//Když chcete iterovat přes vlastnosti, které jsou přímo na objektu a nejsou
|
||||
//zděněné z prototypů, kontrolujte vlastnosti přes hasOwnProperty()
|
||||
var popis = "";
|
||||
var osoba = {prijmeni:"Jan", jmeno:"Novák", vek:18};
|
||||
for (var x in osoba){
|
||||
if (osoba.hasOwnProperty(x)){
|
||||
popis += osoba[x] + " ";
|
||||
}
|
||||
}
|
||||
|
||||
// for-in by neměl být použit pro pole, pokud záleží na pořadí indexů.
|
||||
// Neexistuje jistota, že for-in je vrátí ve správném pořadí.
|
||||
// Příkaz for/of umožňuje iterovat iterovatelné objekty (včetně vestavěných typů
|
||||
// String, Array, například polím podobným argumentům nebo NodeList objektům,
|
||||
// TypeArray, Map a Set, či uživatelsky definované iterovatelné objekty).
|
||||
var myPets = "";
|
||||
var pets = ["cat", "dog", "hamster", "hedgehog"];
|
||||
for (var pet of pets){
|
||||
myPets += pet + " ";
|
||||
} // myPets = 'cat dog hamster hedgehog '
|
||||
|
||||
// && je logické a, || je logické nebo
|
||||
if (dum.velikost == "velký" && dum.barva == "modrá"){
|
||||
dum.obsahuje = "medvěd";
|
||||
}
|
||||
if (barva == "červená" || barva == "modrá"){
|
||||
// barva je červená nebo modtrá
|
||||
// barva je červená nebo modrá
|
||||
}
|
||||
|
||||
// && a || jsou praktické i pro nastavení základních hodnot
|
||||
var jmeno = nejakeJmeno || "default";
|
||||
|
||||
|
||||
// `switch` zkoumá přesnou rovnost (===)
|
||||
// Používejte 'break;' po každé možnosti, jinak se provede i možnost za ní.
|
||||
znamka = 'B';
|
||||
@ -289,8 +306,9 @@ switch (znamka) {
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
// 4. Funckce, Oblast platnosti (scope) a Vnitřní funkce
|
||||
// 4. Funkce, Oblast platnosti (scope) a Vnitřní funkce
|
||||
|
||||
// JavaScriptové funkce jsou definovány slůvkem `function`.
|
||||
function funkce(text){
|
||||
@ -302,12 +320,9 @@ funkce("něco"); // = "NĚCO"
|
||||
// jako slůvko return, jinak se vrátí 'undefined', kvůli automatickému vkládání
|
||||
// středníků. Platí to zejména pro Allmanův styl zápisu.
|
||||
|
||||
function funkce()
|
||||
{
|
||||
function funkce(){
|
||||
return // <- zde je automaticky vložen středník
|
||||
{
|
||||
tohleJe: "vlastnost objektu"
|
||||
}
|
||||
{ tohleJe: "vlastnost objektu"};
|
||||
}
|
||||
funkce(); // = undefined
|
||||
|
||||
@ -327,9 +342,9 @@ function myFunction(){
|
||||
setInterval(myFunction, 5000);
|
||||
|
||||
// Objekty funkcí nemusíme ani deklarovat pomocí jména, můžeme je napsat jako
|
||||
// ananymní funkci přímo vloženou jako argument
|
||||
// anonymní funkci přímo vloženou jako argument
|
||||
setTimeout(function(){
|
||||
// tento kód bude zavolán za 5 vteřin
|
||||
// tento kód bude zavolán za 5 vteřin
|
||||
}, 5000);
|
||||
|
||||
// JavaScript má oblast platnosti funkce, funkce ho mají, ale jiné bloky ne
|
||||
@ -339,21 +354,21 @@ if (true){
|
||||
i; // = 5 - ne undefined, jak byste očekávali v jazyku, kde mají bloky svůj
|
||||
// rámec působnosti
|
||||
|
||||
// Toto je běžný model,který chrání před únikem dočasných proměnných do
|
||||
// Toto je běžný model, který chrání před únikem dočasných proměnných do
|
||||
//globální oblasti
|
||||
(function(){
|
||||
var docasna = 5;
|
||||
// Můžeme přistupovat k globálního oblasti přes přiřazování globalním
|
||||
// Můžeme přistupovat ke globálního oblasti přes přiřazování globálním
|
||||
// objektům. Ve webovém prohlížeči je to vždy 'window`. Globální objekt
|
||||
// může mít v jiných prostředích jako Node.js jinné jméno.
|
||||
// může mít v jiných prostředích jako Node.js jiné jméno.
|
||||
window.trvala = 10;
|
||||
})();
|
||||
docasna; // způsobí ReferenceError
|
||||
trvala; // = 10
|
||||
|
||||
// Jedna z nejvice mocných vlastnosti JavaScriptu je vnitřní funkce. Je to funkce
|
||||
// definovaná v jinné funkci, vnitřní funkce má přístup ke všem proměnným ve
|
||||
// vnější funkci, dokonce i poté, co funkce skončí
|
||||
// Jedna z nejmocnějších vlastností JavaScriptu je vnitřní funkce. Je to funkce
|
||||
// definovaná v jiné funkci. Vnitřní funkce má přístup ke všem proměnným ve
|
||||
// vnější funkci, dokonce i poté, co vnější funkce skončí.
|
||||
function ahojPoPetiVterinach(jmeno){
|
||||
var prompt = "Ahoj, " + jmeno + "!";
|
||||
// Vnitřní funkce je dána do lokální oblasti platnosti, jako kdyby byla
|
||||
@ -362,33 +377,33 @@ function ahojPoPetiVterinach(jmeno){
|
||||
alert(prompt);
|
||||
}
|
||||
setTimeout(vnitrni, 5000);
|
||||
// setTimeout je asynchronní, takže funkce ahojPoPetiVterinach se ukončí
|
||||
// okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak protože
|
||||
// vnitrni je definována přes ahojPoPetiVterinach, má pořád přístup k
|
||||
// setTimeout je asynchronní, takže se funkce ahojPoPetiVterinach ukončí
|
||||
// okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak
|
||||
// vnitrni je definována přes ahojPoPetiVterinach a má pořád přístup k
|
||||
// proměnné prompt, když je konečně zavolána.
|
||||
}
|
||||
ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s
|
||||
|
||||
///////////////////////////////////////////////////
|
||||
// 5. Více o objektech, konstuktorech a prototypech
|
||||
// 5. Více o objektech, konstruktorech a prototypech
|
||||
|
||||
// Objekty můžou obsahovat funkce
|
||||
// Objekty můžou obsahovat funkce.
|
||||
var mujObjekt = {
|
||||
mojeFunkce: function(){
|
||||
return "Ahoj světe!";
|
||||
return "Hello world!";
|
||||
}
|
||||
};
|
||||
mujObjekt.mojeFunkce(); // = "Ahoj světe!"
|
||||
mujObjekt.mojeFunkce(); // = "Hello world!"
|
||||
|
||||
// Když jsou funkce z objektu zavolány, můžou přistupovat k objektu přes slůvko
|
||||
// 'this''
|
||||
var mujObjekt = {
|
||||
text: "Ahoj světe!",
|
||||
text: "Hello world!",
|
||||
mojeFunkce: function(){
|
||||
return this.text;
|
||||
}
|
||||
};
|
||||
mujObjekt.mojeFunkce(); // = "Ahoj světe!"
|
||||
mujObjekt.mojeFunkce(); // = "Hello world!"
|
||||
|
||||
// Slůvko this je nastaveno k tomu, kde je voláno, ne k tomu, kde je definováno
|
||||
// Takže naše funkce nebude fungovat, když nebude v kontextu objektu.
|
||||
@ -396,23 +411,23 @@ var mojeFunkce = mujObjekt.mojeFunkce;
|
||||
mojeFunkce(); // = undefined
|
||||
|
||||
// Opačně, funkce může být přiřazena objektu a může přistupovat k objektu přes
|
||||
// this, i když nebyla přímo v definici-
|
||||
// this, i když nebyla přímo v definici.
|
||||
var mojeDalsiFunkce = function(){
|
||||
return this.text.toUpperCase();
|
||||
}
|
||||
mujObjekt.mojeDalsiFunkce = mojeDalsiFunkce;
|
||||
mujObjekt.mojeDalsiFunkce(); // = "AHOJ SVĚTE!"
|
||||
mujObjekt.mojeDalsiFunkce(); // = "HELLO WORLD!"
|
||||
|
||||
// Můžeme také specifikovat, v jakém kontextu má být funkce volána pomocí
|
||||
// `call` nebo `apply`.
|
||||
|
||||
var dalsiFunkce = function(s){
|
||||
return this.text + s;
|
||||
}
|
||||
dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Ahoj světe! A ahoj měsíci!"
|
||||
};
|
||||
dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Hello world! A ahoj měsíci!"
|
||||
|
||||
// Funkce `apply`je velmi podobná, akorát bere jako druhý argument pole argumentů
|
||||
dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Ahoj světe! A ahoj slunce!"
|
||||
// Funkce `apply`je velmi podobná, pouze bere jako druhý argument pole argumentů
|
||||
dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Hello world! A ahoj slunce!"
|
||||
|
||||
// To je praktické, když pracujete s funkcí, která bere sekvenci argumentů a
|
||||
// chcete předat pole.
|
||||
@ -425,38 +440,42 @@ Math.min.apply(Math, [42, 6, 27]); // = 6
|
||||
// použijte `bind`.
|
||||
|
||||
var pripojenaFunkce = dalsiFunkce.bind(mujObjekt);
|
||||
pripojenaFunkce(" A ahoj Saturne!"); // = "Ahoj světe! A ahoj Saturne!"
|
||||
pripojenaFunkce(" A ahoj Saturne!"); // = "Hello world! A ahoj Saturne!"
|
||||
|
||||
// `bind` může být použito čatečně částečně i k používání
|
||||
// `bind` může být použito částečně k provázání funkcí
|
||||
|
||||
var nasobeni = function(a, b){ return a * b; }
|
||||
var nasobeni = function(a, b){ return a * b; };
|
||||
var zdvojeni = nasobeni.bind(this, 2);
|
||||
zdvojeni(8); // = 16
|
||||
|
||||
// Když zavoláte funkci se slůvkem 'new', vytvoří se nový objekt a
|
||||
// a udělá se dostupný funkcím skrz slůvko 'this'. Funkcím volaným takto se říká
|
||||
// konstruktory
|
||||
// konstruktory.
|
||||
|
||||
var MujKonstruktor = function(){
|
||||
this.mojeCislo = 5;
|
||||
}
|
||||
};
|
||||
mujObjekt = new MujKonstruktor(); // = {mojeCislo: 5}
|
||||
mujObjekt.mojeCislo; // = 5
|
||||
|
||||
// Každý JsavaScriptový objekt má prototyp. Když budete přistupovat k vlasnosti
|
||||
// objektu, který neexistuje na objektu, tak se JS koukne do prototypu.
|
||||
// Na rozdíl od nejznámějších objektově orientovaných jazyků, JavaScript nezná
|
||||
// koncept instancí vytvořených z tříd. Místo toho Javascript kombinuje
|
||||
// vytváření instancí a dědění do konceptu zvaného 'prototyp'.
|
||||
|
||||
// Každý JavaScriptový objekt má prototyp. Když budete přistupovat k vlastnosti
|
||||
// objektu, který neexistuje na objektu, tak se JS podívá do prototypu.
|
||||
|
||||
// Některé JS implementace vám umožní přistupovat k prototypu přes magickou
|
||||
// vlastnost '__proto__'. I když je toto užitečné k vysvětlování prototypů, není
|
||||
// to součást standardu, ke standartní způsobu k používání prototypu se dostaneme
|
||||
// později.
|
||||
// to součást standardu. Ke standardnímu způsobu používání prototypu se
|
||||
// dostaneme později.
|
||||
var mujObjekt = {
|
||||
mujText: "Ahoj svete!"
|
||||
mujText: "Hello world!"
|
||||
};
|
||||
var mujPrototyp = {
|
||||
smyslZivota: 42,
|
||||
mojeFunkce: function(){
|
||||
return this.mujText.toLowerCase()
|
||||
return this.mujText.toLowerCase();
|
||||
}
|
||||
};
|
||||
|
||||
@ -464,7 +483,7 @@ mujObjekt.__proto__ = mujPrototyp;
|
||||
mujObjekt.smyslZivota; // = 42
|
||||
|
||||
// Toto funguje i pro funkce
|
||||
mujObjekt.mojeFunkce(); // = "Ahoj světe!"
|
||||
mujObjekt.mojeFunkce(); // = "Hello world!"
|
||||
|
||||
// Samozřejmě, pokud není vlastnost na vašem prototypu, tak se hledá na
|
||||
// prototypu od prototypu atd.
|
||||
@ -474,21 +493,41 @@ mujPrototyp.__proto__ = {
|
||||
mujObjekt.mujBoolean; // = true
|
||||
|
||||
|
||||
// Zde neni žádné kopírování; každý objekt ukládá referenci na svůj prototyp
|
||||
// Toto znamená, že můžeme měnit prototyp a změny se projeví všude
|
||||
// Zde není žádné kopírování; každý objekt ukládá referenci na svůj prototyp
|
||||
// Toto znamená, že můžeme měnit prototyp a změny se projeví všude.
|
||||
mujPrototyp.smyslZivota = 43;
|
||||
mujObjekt.smyslZivota // = 43
|
||||
mujObjekt.smyslZivota; // = 43
|
||||
|
||||
// Příkaz for/in umožňuje iterovat vlastnosti objektu až do úrovně null
|
||||
// prototypu.
|
||||
for (var x in myObj){
|
||||
console.log(myObj[x]);
|
||||
}
|
||||
///Vypíše:
|
||||
// Hello world!
|
||||
// 43
|
||||
// [Function: myFunc]
|
||||
|
||||
// Pro výpis pouze vlastností patřících danému objektu a nikoli jeho prototypu,
|
||||
// použijte kontrolu pomocí `hasOwnProperty()`.
|
||||
for (var x in myObj){
|
||||
if (myObj.hasOwnProperty(x)){
|
||||
console.log(myObj[x]);
|
||||
}
|
||||
}
|
||||
///Vypíše:
|
||||
// Hello world!
|
||||
|
||||
// Zmínili jsme již předtím, že '__proto__' není ve standardu a není cesta, jak
|
||||
// měnit prototyp existujícího objektu. Avšak existují možnosti, jak vytvořit
|
||||
// nový objekt s daným prototypem
|
||||
// nový objekt s daným prototypem.
|
||||
|
||||
// První je Object.create, což je nedávný přídavek do JS a není dostupný zatím
|
||||
// ve všech implementacích.
|
||||
var mujObjekt = Object.create(mujPrototyp);
|
||||
mujObjekt.smyslZivota // = 43
|
||||
mujObjekt.smyslZivota; // = 43
|
||||
|
||||
// Druhý způsob, který funguje všude je pomocí konstuktoru. Konstruktor má
|
||||
// Druhý způsob, který funguje všude, je pomocí konstruktoru. Konstruktor má
|
||||
// vlastnost jménem prototype. Toto *není* prototyp samotného konstruktoru, ale
|
||||
// prototyp nového objektu.
|
||||
MujKonstruktor.prototype = {
|
||||
@ -499,10 +538,10 @@ MujKonstruktor.prototype = {
|
||||
};
|
||||
var mujObjekt2 = new MujKonstruktor();
|
||||
mujObjekt2.ziskejMojeCislo(); // = 5
|
||||
mujObjekt2.mojeCislo = 6
|
||||
mujObjekt2.mojeCislo = 6;
|
||||
mujObjekt2.ziskejMojeCislo(); // = 6
|
||||
|
||||
// Vestavěnné typy jako čísla nebo řetězce mají také konstruktory, které vytváří
|
||||
// Vestavěné typy jako čísla nebo řetězce mají také konstruktory, které vytváří
|
||||
// ekvivalentní obalovací objekty (wrappery).
|
||||
var mojeCislo = 12;
|
||||
var mojeCisloObj = new Number(12);
|
||||
@ -521,7 +560,7 @@ if (new Number(0)){
|
||||
// a objekty jsou vždy pravdivé
|
||||
}
|
||||
|
||||
// Avšak, obalovací objekty a normální vestavěnné typy sdílejí prototyp, takže
|
||||
// Avšak, obalovací objekty a normální vestavěné typy sdílejí prototyp, takže
|
||||
// můžete přidat funkcionalitu k řetězci
|
||||
String.prototype.prvniZnak = function(){
|
||||
return this.charAt(0);
|
||||
@ -530,45 +569,60 @@ String.prototype.prvniZnak = function(){
|
||||
|
||||
// Tento fakt je často používán v polyfillech, což je implementace novějších
|
||||
// vlastností JavaScriptu do starších variant, takže je můžete používat třeba
|
||||
// ve starých prohlížečích
|
||||
// ve starých prohlížečích.
|
||||
|
||||
// Pro příkklad, zmínili jsme, že Object.create není dostupný ve všech
|
||||
// implementacích, můžeme si avšak přidat pomocí polyfillu
|
||||
// Na příklad jsme zmínili, že Object.create není dostupný ve všech
|
||||
// implementacích, ale můžeme si ho přidat pomocí polyfillu:
|
||||
if (Object.create === undefined){ // nebudeme ho přepisovat, když existuje
|
||||
Object.create = function(proto){
|
||||
// vytvoříme dočasný konstruktor
|
||||
var Constructor = function(){};
|
||||
Constructor.prototype = proto;
|
||||
// ten použijeme k vytvoření nového s prototypem
|
||||
// ten použijeme k vytvoření nového objektu s prototypem
|
||||
return new Constructor();
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Kam dál
|
||||
|
||||
[Mozilla Developer
|
||||
Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) obsahuje
|
||||
perfektní dokumentaci pro JavaScript, který je používaný v prohlížečích. Navíc
|
||||
je to i wiki, takže jakmile se naučíte více, můžete pomoci ostatním, tím, že
|
||||
přispějete svými znalostmi.
|
||||
[Mozilla Developer Network][1] obsahuje perfektní dokumentaci pro JavaScript,
|
||||
který je používaný v prohlížečích. Navíc je to i wiki, takže jakmile se naučíte
|
||||
více, můžete pomoci ostatním tím, že přispějete svými znalostmi.
|
||||
|
||||
MDN's [A re-introduction to
|
||||
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
||||
MDN's [A re-introduction to JavaScript][2]
|
||||
pojednává o konceptech vysvětlených zde v mnohem větší hloubce. Tento návod
|
||||
pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit více, jak se používá
|
||||
na webových stránkách, začněte tím, že se kouknete na [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
|
||||
pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit, jak se používá
|
||||
na webových stránkách, začněte tím, že se podíváte na [DOM][3]
|
||||
|
||||
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) je varianta tohoto
|
||||
návodu i s úkoly-
|
||||
[Learn Javascript by Example and with Challenges][4]
|
||||
je varianta tohoto návodu i s úkoly.
|
||||
|
||||
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) je sbírka
|
||||
příkladů těch nejvíce nepředvídatelných částí tohoto jazyka.
|
||||
[JavaScript Garden][5] je sbírka příkladů těch nejnepředvídatelnějších částí
|
||||
tohoto jazyka.
|
||||
|
||||
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/)
|
||||
je klasická výuková kniha.
|
||||
[JavaScript: The Definitive Guide][6] je klasická výuková kniha.
|
||||
|
||||
Jako dodatek k přímým autorům tohoto článku, některý obsah byl přizpůsoben z
|
||||
Pythoního tutoriálu od Louie Dinh na této stráce, a z [JS
|
||||
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
||||
z Mozilla Developer Network.
|
||||
[Eloquent Javascript][8] od Marijn Haverbeke je výbornou JS knihou/e-knihou.
|
||||
|
||||
[Javascript: The Right Way][10] je průvodcem JavaScriptem pro začínající
|
||||
vývojáře i pomocníkem pro zkušené vývojáře, kteří si chtějí prohloubit své
|
||||
znalosti.
|
||||
|
||||
[Javascript:Info][11] je moderním JavaScriptovým průvodcem, který pokrývá
|
||||
základní i pokročilé témata velice výstižným výkladem.
|
||||
|
||||
Jako dodatek k přímým autorům tohoto článku byly na těchto stránkách části
|
||||
obsahu převzaty z Pythonního tutoriálu Louiho Dinha, a tak0 z [JS Tutorial][7]
|
||||
na stránkách 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/
|
||||
[10]: http://jstherightway.org/
|
||||
[11]: https://javascript.info/
|
||||
|
@ -13,7 +13,7 @@ Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce či
|
||||
a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha
|
||||
dalších formátů)
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<!-- 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
|
||||
|
@ -135,6 +135,10 @@ selector::after {}
|
||||
.parent * { } /* all descendants */
|
||||
.parent > * { } /* all children */
|
||||
|
||||
/* Group any number of selectors to define styles that affect all selectors
|
||||
in the group */
|
||||
selector1, selector2 { }
|
||||
|
||||
/* ####################
|
||||
## PROPERTIES
|
||||
#################### */
|
||||
|
@ -16,19 +16,19 @@ Nodes
|
||||
|
||||
**Represents a record in a graph.**
|
||||
|
||||
```()```
|
||||
`()`
|
||||
It's an empty *node*, to indicate that there is a *node*, but it's not relevant for the query.
|
||||
|
||||
```(n)```
|
||||
`(n)`
|
||||
It's a *node* referred by the variable **n**, reusable in the query. It begins with lowercase and uses camelCase.
|
||||
|
||||
```(p:Person)```
|
||||
`(p:Person)`
|
||||
You can add a *label* to your node, here **Person**. It's like a type / a class / a category. It begins with uppercase and uses camelCase.
|
||||
|
||||
```(p:Person:Manager)```
|
||||
`(p:Person:Manager)`
|
||||
A node can have many *labels*.
|
||||
|
||||
```(p:Person {name : 'Théo Gauchoux', age : 22})```
|
||||
`(p:Person {name : 'Théo Gauchoux', age : 22})`
|
||||
A node can have some *properties*, here **name** and **age**. It begins with lowercase and uses camelCase.
|
||||
|
||||
The types allowed in properties :
|
||||
@ -40,7 +40,7 @@ The types allowed in properties :
|
||||
|
||||
*Warning : there isn't datetime property in Cypher ! You can use String with a specific pattern or a Numeric from a specific date.*
|
||||
|
||||
```p.name```
|
||||
`p.name`
|
||||
You can access to a property with the dot style.
|
||||
|
||||
|
||||
@ -49,16 +49,16 @@ Relationships (or Edges)
|
||||
|
||||
**Connects two nodes**
|
||||
|
||||
```[:KNOWS]```
|
||||
`[:KNOWS]`
|
||||
It's a *relationship* with the *label* **KNOWS**. It's a *label* as the node's label. It begins with uppercase and use UPPER_SNAKE_CASE.
|
||||
|
||||
```[k:KNOWS]```
|
||||
`[k:KNOWS]`
|
||||
The same *relationship*, referred by the variable **k**, reusable in the query, but it's not necessary.
|
||||
|
||||
```[k:KNOWS {since:2017}]```
|
||||
`[k:KNOWS {since:2017}]`
|
||||
The same *relationship*, with *properties* (like *node*), here **since**.
|
||||
|
||||
```[k:KNOWS*..4]```
|
||||
`[k:KNOWS*..4]`
|
||||
It's a structural information to use in a *path* (seen later). Here, **\*..4** says "Match the pattern, with the relationship **k** which be repeated between 1 and 4 times.
|
||||
|
||||
|
||||
@ -67,16 +67,16 @@ Paths
|
||||
|
||||
**The way to mix nodes and relationships.**
|
||||
|
||||
```(a:Person)-[:KNOWS]-(b:Person)```
|
||||
`(a:Person)-[:KNOWS]-(b:Person)`
|
||||
A path describing that **a** and **b** know each other.
|
||||
|
||||
```(a:Person)-[:MANAGES]->(b:Person)```
|
||||
`(a:Person)-[:MANAGES]->(b:Person)`
|
||||
A path can be directed. This path describes that **a** is the manager of **b**.
|
||||
|
||||
```(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)```
|
||||
`(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)`
|
||||
You can chain multiple relationships. This path describes the friend of a friend.
|
||||
|
||||
```(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)```
|
||||
`(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)`
|
||||
A chain can also be directed. This path describes that **a** is the boss of **b** and the big boss of **c**.
|
||||
|
||||
Patterns often used (from Neo4j doc) :
|
||||
@ -230,13 +230,13 @@ DELETE n, r
|
||||
Other useful clauses
|
||||
---
|
||||
|
||||
```PROFILE```
|
||||
`PROFILE`
|
||||
Before a query, show the execution plan of it.
|
||||
|
||||
```COUNT(e)```
|
||||
`COUNT(e)`
|
||||
Count entities (nodes or relationships) matching **e**.
|
||||
|
||||
```LIMIT x```
|
||||
`LIMIT x`
|
||||
Limit the result to the x first results.
|
||||
|
||||
|
||||
|
@ -500,8 +500,8 @@ main() {
|
||||
|
||||
Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
|
||||
useful Try Dart online.
|
||||
http://www.dartlang.org/
|
||||
http://try.dartlang.org/
|
||||
[https://www.dartlang.org](https://www.dartlang.org)
|
||||
[https://try.dartlang.org](https://try.dartlang.org)
|
||||
|
||||
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: LOLCODE
|
||||
filename: learnLOLCODE.lol
|
||||
filename: learnLOLCODE-de.lol
|
||||
contributors:
|
||||
- ["abactel", "https://github.com/abactel"]
|
||||
translators:
|
||||
|
@ -180,7 +180,7 @@ esac
|
||||
|
||||
# 'for' Schleifen iterieren über die angegebene Zahl von Argumenten:
|
||||
# Der Inhalt von $Variable wird dreimal ausgedruckt.
|
||||
for $Variable in {1..3}
|
||||
for Variable in {1..3}
|
||||
do
|
||||
echo "$Variable"
|
||||
done
|
||||
|
77
de-de/dynamic-programming-de.html.markdown
Normal file
77
de-de/dynamic-programming-de.html.markdown
Normal file
@ -0,0 +1,77 @@
|
||||
---
|
||||
category: Algorithms & Data Structures
|
||||
name: Dynamic Programming
|
||||
contributors:
|
||||
- ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
|
||||
translators:
|
||||
- ["Henrik Jürges", "http://github.com/santifa"]
|
||||
lang: de-de
|
||||
---
|
||||
|
||||
# Dynamische Programmierung
|
||||
|
||||
## Einführung
|
||||
Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung
|
||||
einer bestimmten Klasse von Problemen verwendet wird.
|
||||
Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe
|
||||
gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu
|
||||
vermeiden, das gleiche Problem noch einmal zu lösen.
|
||||
|
||||
Denken Sie immer daran!
|
||||
"Diejenigen, die sich nicht an die Vergangenheit erinnern können,
|
||||
sind dazu verdammt, sie zu wiederholen."
|
||||
|
||||
## Wege zur Lösung solcher Probleme
|
||||
|
||||
1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen.
|
||||
Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die
|
||||
gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und
|
||||
speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr
|
||||
intuitiv. Er wird als Memoization bezeichnet.
|
||||
|
||||
2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher
|
||||
Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der
|
||||
Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird
|
||||
sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden.
|
||||
Dies wird als Dynamische Programmierung bezeichnet.
|
||||
|
||||
## Ein Beispiel für Dynamische Programmierung
|
||||
|
||||
Das Problem mit der längsten ansteigenden Subsequenz besteht darin,
|
||||
die längste ansteigende Subsequenz einer gegebenen Sequenz zu finden.
|
||||
Gegeben die Sequenz `S= {a1, a2, a3, a3, a4,..............., an-1, an }`,
|
||||
müssen wir die größte Teilmenge finden, so daß für alle `j` und `i`, `j<i`
|
||||
in der Teilmenge `aj<ai` gilt.
|
||||
Zuerst müssen wir bei jedem Index i den Wert der längsten Subsequenzen (LSi)
|
||||
finden, wobei das letzte Element der Sequenz ai ist. Dann wäre die größte LSi
|
||||
die längste Subsequenz in der gegebenen Sequenz. Am Anfang wird der LSi mit
|
||||
eins belegt, da ai ein Element der Sequenz (Letztes Element) ist.
|
||||
Dann ist für alle `j` mit `j<i` und `aj<ai`, so dass wir den größten LSj finden
|
||||
und zum LSi hinzufügen. Der Algorithmus hat eine Laufzeit von *O(n2)*.
|
||||
|
||||
Pseudocode zur Bestimmung der Länge der am längsten ansteigenden Subsequenz:
|
||||
Die Komplexität des Algorithmus könnte durch eine bessere Datenstruktur anstelle
|
||||
von Arrays reduziert werden. Das Speichern von Vorgänger-Array's und Variablen
|
||||
wie `largest_sequences_so_far` und dessen Index würde eine Menge Zeit sparen.
|
||||
|
||||
Ein ähnliches Konzept könnte auch bei der Suche nach dem längsten Weg
|
||||
in gerichteten azyklischen Graphen angewandt werden.
|
||||
```python
|
||||
for i=0 to n-1
|
||||
LS[i]=1
|
||||
for j=0 to i-1
|
||||
if (a[i] > a[j] and LS[i]<LS[j])
|
||||
LS[i] = LS[j]+1
|
||||
for i=0 to n-1
|
||||
if (largest < LS[i])
|
||||
```
|
||||
|
||||
### Einige bekannte DP Probleme
|
||||
|
||||
- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]()
|
||||
- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]()
|
||||
- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]()
|
||||
|
||||
## Online Ressourcen
|
||||
|
||||
* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming)
|
@ -10,7 +10,7 @@ lang: de-de
|
||||
|
||||
Git ist eine verteilte Versions- und Quellcodeverwaltung.
|
||||
|
||||
Es nimmt Schnappschüsse der Projekte, um mit diesen Schnappschüssen verschiedene Versionen unterscheiden und den Quellcode verwalten zu können.
|
||||
Es nimmt Schnappschüsse der Projekte auf, um mit diesen Schnappschüssen verschiedene Versionen unterscheiden und den Quellcode verwalten zu können.
|
||||
|
||||
Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* oder *Head* sind idiomatische Bestandteile im Umgang mit Git. Sie wurden nicht übersetzt.
|
||||
|
||||
@ -43,7 +43,7 @@ Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichn
|
||||
|
||||
### Repository (Repo)
|
||||
|
||||
Ein Satz von Dateien, Verzeichnisen, Historieneinträgen, Commits und Heads. Stell es dir wie eine Quellcode-Datenstruktur vor, unter anderem mit der Eigenschaft, dass alle *Elemente* dir Zugriff auf die Revisionshistorie geben.
|
||||
Ein Satz von Dateien, Verzeichnissen, Historieneinträgen, Commits und Heads. Stell es dir wie eine Quellcode-Datenstruktur vor, unter anderem mit der Eigenschaft, dass alle *Elemente* dir Zugriff auf die Revisionshistorie geben.
|
||||
|
||||
Ein Repository besteht in Git aus dem .git-Verzeichnis und dem Arbeitsverzeichnis.
|
||||
|
||||
@ -66,7 +66,7 @@ Ein Commit ist ein Schnappschuss von Änderungen in deinem Arbeitsverzeichnis. W
|
||||
|
||||
### Branch
|
||||
|
||||
Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, den du gemacht hast. Während des Commits wird der Pointer automatisch auf Stand gebracht und zeigt dann auf den neuen letzten Commit.
|
||||
Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, den du gemacht hast. Während des Commits wird der Pointer automatisch auf diesen Stand gebracht und zeigt dann auf den neuen letzten Commit.
|
||||
|
||||
### HEAD und head (Teil des .git-Verzeichnisses)
|
||||
|
||||
@ -215,7 +215,7 @@ $ git commit --amend -m "Correct message"
|
||||
|
||||
### diff
|
||||
|
||||
Zeigt die Unterschiede zwischen Dateien von Arbeitsverzeichnisse, dem Index und Commits an.
|
||||
Zeigt die Unterschiede zwischen Dateien vom Arbeitsverzeichnis, dem Index und Commits an.
|
||||
|
||||
```bash
|
||||
# Unterschiede zwischen deinem Arbeitsverzeichnis und dem Index anzeigen
|
||||
@ -330,7 +330,7 @@ $ git push origin master
|
||||
|
||||
### rebase (mit Vorsicht einsetzen)
|
||||
|
||||
Nimm alle Änderungen, die in einem Branch durch Commits vorgenommen wurden, und übertrage sie auf einen anderen Branch. Achtung: Führe keinen Rebase von Commits durch, die auf ein öffentliches Repo gepusht wurden.
|
||||
Nimm alle Änderungen, die in einem Branch durch Commits vorgenommen wurden, und übertrage sie auf einen anderen Branch. Achtung: Führe keinen Rebase von Commits durch, die auf ein öffentliches Repo gepusht wurden!
|
||||
|
||||
```bash
|
||||
# Rebase "experimentBranch" in den "master"-Branch
|
||||
|
@ -94,7 +94,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
|
||||
|
||||
// Arrays haben bei Kompile-Zeit festgelegte Größen
|
||||
var a4 [4]int // Ein Array mit 4 ints, alle mit Initialwert 0
|
||||
a3 := [...]int{3, 1, 5} // Ein Array mit 4 ints, Initialwerte wie angezeigt
|
||||
a3 := [...]int{3, 1, 5} // Ein Array mit 3 ints, Initialwerte wie angezeigt
|
||||
|
||||
// "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre
|
||||
// Vorzüge, aber slices werden viel häufiger verwendet
|
||||
|
43
de-de/hq9+-de.html.markdown
Normal file
43
de-de/hq9+-de.html.markdown
Normal file
@ -0,0 +1,43 @@
|
||||
---
|
||||
language: HQ9+
|
||||
filename: hq9+.html
|
||||
contributors:
|
||||
- ["Alexey Nazaroff", "https://github.com/rogaven"]
|
||||
translators:
|
||||
- ["Dennis Keller", "https://github.com/denniskeller"]
|
||||
lang: de-de
|
||||
---
|
||||
|
||||
HQ9+ ist eine Parodie auf esoterische Programmiersprachen und wurde von Cliff Biffle kreiert.
|
||||
Die Sprache hat nur vier Befehle und ist nicht Turing-vollständig.
|
||||
|
||||
```
|
||||
Es gibt nur vier Befehle, die durch die folgenden vier Zeichen dargestellt werden
|
||||
H: druckt "Hello, world!"
|
||||
Q: druckt den Quellcode des Programms (ein Quine)
|
||||
9: druckt den Liedtext von "99 Bottles of Beer"
|
||||
+: erhöhe den Akkumulator um Eins (Der Wert des Akkumulators kann nicht gelesen werden)
|
||||
Jedes andere Zeichen wird ignoriert.
|
||||
|
||||
Ok. Lass uns ein Programm schreiben:
|
||||
HQ
|
||||
|
||||
Ergebnis:
|
||||
Hello world!
|
||||
HQ
|
||||
|
||||
HQ9+ ist zwar sehr simpel, es erlaubt aber dir Sachen zu machen, die in
|
||||
anderen Sprachen sehr schwierig sind. Zum Beispiel druckt das folgende Programm
|
||||
drei Mal Kopien von sich selbst auf den Bildschirm:
|
||||
QQQ
|
||||
Dies druckt:
|
||||
QQQ
|
||||
QQQ
|
||||
QQQ
|
||||
```
|
||||
|
||||
Und das ist alles. Es gibt sehr viele Interpreter für HQ9+.
|
||||
Unten findest du einen von ihnen.
|
||||
|
||||
+ [One of online interpreters](https://almnet.de/esolang/hq9plus.php)
|
||||
+ [HQ9+ official website](http://cliffle.com/esoterica/hq9plus.html)
|
@ -2,6 +2,7 @@
|
||||
language: make
|
||||
contributors:
|
||||
- ["Robert Steed", "https://github.com/robochat"]
|
||||
- ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
|
||||
translators:
|
||||
- ["Martin Schimandl", "https://github.com/Git-Jiro"]
|
||||
filename: Makefile-de
|
||||
@ -58,7 +59,7 @@ file2.txt file3.txt: file0.txt file1.txt
|
||||
touch file3.txt
|
||||
|
||||
# Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt.
|
||||
# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
|
||||
# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
|
||||
# Voraussetzungen hinzuzufügen.
|
||||
|
||||
#-----------------------------------------------------------------------
|
||||
@ -182,9 +183,9 @@ echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb
|
||||
# Ein paar Variablen die von Make automatisch definiert werden.
|
||||
echo_inbuilt:
|
||||
echo $(CC)
|
||||
echo ${CXX)}
|
||||
echo ${CXX}
|
||||
echo $(FC)
|
||||
echo ${CFLAGS)}
|
||||
echo ${CFLAGS}
|
||||
echo $(CPPFLAGS)
|
||||
echo ${CXXFLAGS}
|
||||
echo $(LDFLAGS)
|
||||
|
@ -14,7 +14,7 @@ Syntax, in der sich Dokumente leicht schreiben *und* lesen lassen. Außerdem
|
||||
sollte Markdown sich leicht nach HTML (und in andere Formate) konvertieren
|
||||
lassen.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<!-- Markdown ist eine Obermenge von HTML - jede valide HTML-Datei ist also
|
||||
automatisch valides Markdown - was heisst dass wir jedes HTML-Element (also auch
|
||||
Kommentare) in Markdown benutzen können, ohne dass der Parser sie verändert.
|
||||
@ -253,4 +253,4 @@ Ganz schön hässlich | vielleicht doch lieber | wieder aufhören
|
||||
|
||||
Mehr Informationen gibt es in [John Gruber's offiziellem Blog-Post](http://daringfireball.net/projects/markdown/syntax)
|
||||
und bei Adam Pritchards [grandiosem Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
||||
Infos zu GitHub Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown).
|
||||
Infos zu GitHub Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown).
|
||||
|
153
de-de/opencv-de.html.markdown
Normal file
153
de-de/opencv-de.html.markdown
Normal file
@ -0,0 +1,153 @@
|
||||
---
|
||||
category: tool
|
||||
tool: OpenCV
|
||||
filename: learnopencv.py
|
||||
contributors:
|
||||
- ["Yogesh Ojha", "http://github.com/yogeshojha"]
|
||||
translators:
|
||||
- ["Dennis Keller", "https://github.com/denniskeller"]
|
||||
lang: de-de
|
||||
---
|
||||
### Opencv
|
||||
|
||||
OpenCV (Open Source Computer Vision) ist eine Bibliothek von Programmierfunktionen,
|
||||
die hauptsächlich auf maschinelles Sehen in Echtzeit ausgerichtet ist.
|
||||
Ursprünglich wurde OpenCV von Intel entwickelt. Später wurde es von von
|
||||
Willow Garage und dann Itseez (das später von Intel übernommen wurde) unterstützt.
|
||||
OpenCV unterstützt derzeit eine Vielzahl von Sprachen, wie C++, Python, Java uvm.
|
||||
|
||||
#### Installation
|
||||
|
||||
Bitte lese diese Artikel für die Installation von OpenCV auf deinen Computer.
|
||||
|
||||
* Windows Installationsanleitung: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]()
|
||||
* Mac Installationsanleitung (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]()
|
||||
* Linux Installationsanleitung (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]()
|
||||
|
||||
### Hier werden wir uns auf die Pythonimplementierung von OpenCV konzentrieren.
|
||||
|
||||
```python
|
||||
# Bild in OpenCV lesen
|
||||
import cv2
|
||||
img = cv2.imread('Katze.jpg')
|
||||
|
||||
# Bild darstellen
|
||||
# Die imshow() Funktion wird verwendet um das Display darzustellen.
|
||||
cv2.imshow('Image',img)
|
||||
# Das erste Argument ist der Titel des Fensters und der zweite Parameter ist das Bild
|
||||
# Wenn du den Fehler Object Type None bekommst ist eventuell dein Bildpfad falsch.
|
||||
# Bitte überprüfe dann den Pfad des Bildes erneut.
|
||||
cv2.waitKey(0)
|
||||
# waitKey() ist eine Tastaturbindungsfunktion, sie nimmt Argumente in
|
||||
# Millisekunden an. Für GUI Ereignisse MUSST du die waitKey() Funktion verwenden.
|
||||
|
||||
# Ein Bild schreiben
|
||||
cv2.imwrite('graueKatze.png',img)
|
||||
# Das erste Arkument ist der Dateiname und das Zweite ist das Bild
|
||||
|
||||
# Konveriere das Bild zu Graustufen
|
||||
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
# Videoaufnahme von der Webcam
|
||||
cap = cv2.VideoCapture(0)
|
||||
# 0 ist deine Kamera, wenn du mehrere Kameras hast musst du deren Id eingeben
|
||||
while(True):
|
||||
# Erfassen von Einzelbildern
|
||||
_, frame = cap.read()
|
||||
cv2.imshow('Frame',frame)
|
||||
# Wenn der Benutzer q drückt -> beenden
|
||||
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||
break
|
||||
# Die Kamera muss wieder freigegeben werden
|
||||
cap.release()
|
||||
|
||||
# Wiedergabe von Videos aus einer Datei
|
||||
cap = cv2.VideoCapture('film.mp4')
|
||||
while(cap.isOpened()):
|
||||
_, frame = cap.read()
|
||||
# Das Video in Graustufen abspielen
|
||||
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||||
cv2.imshow('frame',gray)
|
||||
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||
break
|
||||
cap.release()
|
||||
|
||||
# Zeichne eine Linie in OpenCV
|
||||
# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness)
|
||||
cv2.line(img,(0,0),(511,511),(255,0,0),5)
|
||||
|
||||
# Zeichne ein Rechteck
|
||||
# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness)
|
||||
# thickness = -1 wird zum Füllen des Rechtecks verwendet
|
||||
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
|
||||
|
||||
# Zeichne ein Kreis
|
||||
cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness)
|
||||
cv2.circle(img,(200,90), 100, (0,0,255), -1)
|
||||
|
||||
# Zeichne eine Ellipse
|
||||
cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
|
||||
|
||||
# Text auf Bildern hinzufügen
|
||||
cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
|
||||
|
||||
# Bilder zusammenfüggen
|
||||
img1 = cv2.imread('Katze.png')
|
||||
img2 = cv2.imread('openCV.jpg')
|
||||
dst = cv2.addWeighted(img1,0.5,img2,0.5,0)
|
||||
|
||||
# Schwellwertbild
|
||||
# Binäre Schwellenwerte
|
||||
_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
|
||||
# Anpassbare Schwellenwerte
|
||||
adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
|
||||
|
||||
# Weichzeichnung von einem Bild
|
||||
# Gausßscher Weichzeichner
|
||||
blur = cv2.GaussianBlur(img,(5,5),0)
|
||||
# Rangordnungsfilter
|
||||
medianBlur = cv2.medianBlur(img,5)
|
||||
|
||||
# Canny-Algorithmus
|
||||
img = cv2.imread('Katze.jpg',0)
|
||||
edges = cv2.Canny(img,100,200)
|
||||
|
||||
# Gesichtserkennung mit Haarkaskaden
|
||||
# Lade die Haarkaskaden von https://github.com/opencv/opencv/blob/master/data/haarcascades/ herunter
|
||||
import cv2
|
||||
import numpy as np
|
||||
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
|
||||
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
|
||||
|
||||
img = cv2.imread('Mensch.jpg')
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
aces = face_cascade.detectMultiScale(gray, 1.3, 5)
|
||||
for (x,y,w,h) in faces:
|
||||
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
|
||||
roi_gray = gray[y:y+h, x:x+w]
|
||||
roi_color = img[y:y+h, x:x+w]
|
||||
eyes = eye_cascade.detectMultiScale(roi_gray)
|
||||
for (ex,ey,ew,eh) in eyes:
|
||||
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
|
||||
|
||||
cv2.imshow('img',img)
|
||||
cv2.waitKey(0)
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
# destroyAllWindows() zerstört alle Fenster
|
||||
# Wenn du ein bestimmtes Fenter zerstören möchtest musst du den genauen Namen des
|
||||
# von dir erstellten Fensters übergeben.
|
||||
```
|
||||
|
||||
### Weiterführende Literatur:
|
||||
* Lade Kaskade hier herunter [https://github.com/opencv/opencv/blob/master/data/haarcascades]()
|
||||
* OpenCV Zeichenfunktionen [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]()
|
||||
* Eine aktuelle Sprachenreferenz kann hier gefunden werden [https://opencv.org]()
|
||||
* Zusätzliche Ressourcen können hier gefunden werden [https://en.wikipedia.org/wiki/OpenCV]()
|
||||
* Gute OpenCV Tutorials
|
||||
* [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]()
|
||||
* [https://realpython.com/python-opencv-color-spaces]()
|
||||
* [https://pyimagesearch.com]()
|
||||
* [https://www.learnopencv.com]()
|
||||
* [https://docs.opencv.org/master/]()
|
200
de-de/paren-de.html.markdown
Normal file
200
de-de/paren-de.html.markdown
Normal file
@ -0,0 +1,200 @@
|
||||
---
|
||||
|
||||
language: Paren
|
||||
filename: learnparen.paren
|
||||
contributors:
|
||||
- ["KIM Taegyoon", "https://github.com/kimtg"]
|
||||
- ["Claudson Martins", "https://github.com/claudsonm"]
|
||||
translators:
|
||||
- ["Dennis Keller", "https://github.com/denniskeller"]
|
||||
lang: de-de
|
||||
---
|
||||
|
||||
[Paren](https://bitbucket.org/ktg/paren) ist ein Dialekt von Lisp.
|
||||
Es ist als eingebettete Sprache konzipiert.
|
||||
|
||||
Manche Beispiele sind von <http://learnxinyminutes.com/docs/racket/>.
|
||||
|
||||
```scheme
|
||||
;;; Kommentare
|
||||
# Kommentare
|
||||
|
||||
;; Einzeilige Kommentare starten mit einem Semikolon oder einem Hashtag
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 1. Primitive Datentypen und Operatoren
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;;; Zahlen
|
||||
123 ; int
|
||||
3.14 ; double
|
||||
6.02e+23 ; double
|
||||
(int 3.14) ; => 3 : int
|
||||
(double 123) ; => 123 : double
|
||||
|
||||
;; Funktionsapplikationen werden so geschrieben: (f x y z ...)
|
||||
;; Dabei ist f eine Funktion und x, y, z sind die Operatoren.
|
||||
;; Wenn du eine Literalliste von Daten erstelllen möchtest,
|
||||
;; verwende (quote) um zu verhindern, dass sie ausgewertet zu werden.
|
||||
(quote (+ 1 2)) ; => (+ 1 2)
|
||||
;; Nun einige arithmetische Operationen
|
||||
(+ 1 1) ; => 2
|
||||
(- 8 1) ; => 7
|
||||
(* 10 2) ; => 20
|
||||
(^ 2 3) ; => 8
|
||||
(/ 5 2) ; => 2
|
||||
(% 5 2) ; => 1
|
||||
(/ 5.0 2) ; => 2.5
|
||||
|
||||
;;; Wahrheitswerte
|
||||
true ; for Wahr
|
||||
false ; for Falsch
|
||||
(! true) ; => Falsch
|
||||
(&& true false (prn "doesn't get here")) ; => Falsch
|
||||
(|| false true (prn "doesn't get here")) ; => Wahr
|
||||
|
||||
;;; Zeichen sind Ints.
|
||||
(char-at "A" 0) ; => 65
|
||||
(chr 65) ; => "A"
|
||||
|
||||
;;; Zeichenketten sind ein Array von Zahlen mit fester Länge.
|
||||
"Hello, world!"
|
||||
"Benjamin \"Bugsy\" Siegel" ; Backslash ist ein Escape-Zeichen
|
||||
"Foo\tbar\r\n" ; beinhaltet C Escapes: \t \r \n
|
||||
|
||||
;; Zeichenketten können auch verbunden werden!
|
||||
(strcat "Hello " "world!") ; => "Hello world!"
|
||||
|
||||
;; Eine Zeichenketten kann als Liste von Zeichen behandelt werden
|
||||
(char-at "Apple" 0) ; => 65
|
||||
|
||||
;; Drucken ist ziemlich einfach
|
||||
(pr "Ich bin" "Paren. ") (prn "Schön dich zu treffen!")
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 2. Variablen
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Du kannst Variablen setzen indem du (set) verwedest
|
||||
;; eine Variable kann alle Zeichen besitzen außer: ();#"
|
||||
(set some-var 5) ; => 5
|
||||
some-var ; => 5
|
||||
|
||||
;; Zugriff auf eine zuvor nicht zugewiesene Variable erzeugt eine Ausnahme
|
||||
; x ; => Unknown variable: x : nil
|
||||
|
||||
;; Lokale Bindung: Verwende das Lambda Calculus! 'a' und 'b'
|
||||
;; sind nur zu '1' und '2' innerhalb von (fn ...) gebunden.
|
||||
((fn (a b) (+ a b)) 1 2) ; => 3
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 3. Sammlungen
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;;; Listen
|
||||
|
||||
;; Listen sind Vektrorartige Datenstrukturen. (Zufälliger Zugriff ist O(1).
|
||||
(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3)
|
||||
;; 'list' ist ein komfortabler variadischer Konstruktor für Listen
|
||||
(list 1 2 3) ; => (1 2 3)
|
||||
;; und ein quote kann als literaler Listwert verwendet werden
|
||||
(quote (+ 1 2)) ; => (+ 1 2)
|
||||
|
||||
;; Du kannst 'cons' verwenden um ein Element an den Anfang einer Liste hinzuzufügen.
|
||||
(cons 0 (list 1 2 3)) ; => (0 1 2 3)
|
||||
|
||||
;; Listen sind ein sehr einfacher Typ, daher gibt es eine Vielzahl an Funktionen
|
||||
;; für Sie. Ein paar Beispiele:
|
||||
(map inc (list 1 2 3)) ; => (2 3 4)
|
||||
(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4)
|
||||
(length (list 1 2 3 4)) ; => 4
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 3. Funktionen
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Verwende 'fn' um Funktionen zu erstellen.
|
||||
;; eine Funktion gibt immer den Wert ihres letzten Ausdrucks zurück
|
||||
(fn () "Hello World") ; => (fn () Hello World) : fn
|
||||
|
||||
;; Verwende Klammern um alle Funktionen aufzurufen, inklusive Lambda Ausdrücke
|
||||
((fn () "Hello World")) ; => "Hello World"
|
||||
|
||||
;; Zuweisung einer Funktion zu einer Variablen
|
||||
(set hello-world (fn () "Hello World"))
|
||||
(hello-world) ; => "Hello World"
|
||||
|
||||
;; Du kannst dies mit syntaktischen Zucker für die Funktionsdefinition verkürzen:
|
||||
(defn hello-world2 () "Hello World")
|
||||
|
||||
;; Die () von oben ist eine Liste von Argumente für die Funktion.
|
||||
(set hello
|
||||
(fn (name)
|
||||
(strcat "Hello " name)))
|
||||
(hello "Steve") ; => "Hello Steve"
|
||||
|
||||
;; ... oder gleichwertig, unter Verwendung mit syntaktischen Zucker:
|
||||
(defn hello2 (name)
|
||||
(strcat "Hello " name))
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 4. Gleichheit
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Für Zahlen verwende '=='
|
||||
(== 3 3.0) ; => wahr
|
||||
(== 2 1) ; => falsch
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 5. Kontrollfluss
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;;; Bedingungen
|
||||
|
||||
(if true ; test Ausdruck
|
||||
"this is true" ; then Ausdruck
|
||||
"this is false") ; else Ausdruck
|
||||
; => "this is true"
|
||||
|
||||
;;; Schleifen
|
||||
|
||||
;; for Schleifen ist für Zahlen
|
||||
;; (for SYMBOL START ENDE SCHRITT AUSDRUCK ..)
|
||||
(for i 0 10 2 (pr i "")) ; => schreibt 0 2 4 6 8 10
|
||||
(for i 0.0 10 2.5 (pr i "")) ; => schreibt 0 2.5 5 7.5 10
|
||||
|
||||
;; while Schleife
|
||||
((fn (i)
|
||||
(while (< i 10)
|
||||
(pr i)
|
||||
(++ i))) 0) ; => schreibt 0123456789
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 6. Mutation
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Verwende 'set' um einer Variablen oder einer Stelle einen neuen Wert zuzuweisen.
|
||||
(set n 5) ; => 5
|
||||
(set n (inc n)) ; => 6
|
||||
n ; => 6
|
||||
(set a (list 1 2)) ; => (1 2)
|
||||
(set (nth 0 a) 3) ; => 3
|
||||
a ; => (3 2)
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; 7. Makros
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
;; Makros erlauben es dir die Syntax der Sprache zu erweitern.
|
||||
;; Parens Makros sind einfach.
|
||||
;; Tatsächlich ist (defn) ein Makro.
|
||||
(defmacro setfn (name ...) (set name (fn ...)))
|
||||
(defmacro defn (name ...) (def name (fn ...)))
|
||||
|
||||
;; Lass uns eine Infix Notation hinzufügen
|
||||
;; Let's add an infix notation
|
||||
(defmacro infix (a op ...) (op a ...))
|
||||
(infix 1 + 2 (infix 3 * 4)) ; => 15
|
||||
|
||||
;; Makros sind nicht hygenisch, Du kannst bestehende Variablen überschreiben!
|
||||
;; Sie sind Codetransformationenen.
|
||||
```
|
@ -152,7 +152,7 @@ print("Ich bin Python. Schön, dich kennenzulernen!")
|
||||
some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm
|
||||
some_var #=> 5
|
||||
|
||||
# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus.
|
||||
# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus.
|
||||
# Unter "Kontrollstruktur" kann noch mehr über
|
||||
# Ausnahmebehandlung erfahren werden.
|
||||
some_unknown_var # Löst einen NameError aus
|
||||
@ -225,7 +225,7 @@ a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
|
||||
# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen
|
||||
d, e, f = 4, 5, 6
|
||||
# Es ist kinderleicht zwei Werte zu tauschen
|
||||
e, d = d, e # d is now 5 and e is now 4
|
||||
e, d = d, e # d ist nun 5 und e ist nun 4
|
||||
|
||||
|
||||
# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare
|
||||
@ -379,8 +379,8 @@ with open("meineDatei.txt") as f:
|
||||
print(line)
|
||||
|
||||
# Python bietet ein fundamentales Konzept der Iteration.
|
||||
# Das Objekt, auf das die Interation, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable".
|
||||
# Die range Method gibt ein solches Objekt aus.
|
||||
# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable".
|
||||
# Die range Methode gibt ein solches Objekt aus.
|
||||
|
||||
filled_dict = {"one": 1, "two": 2, "three": 3}
|
||||
our_iterable = filled_dict.keys()
|
||||
@ -396,8 +396,8 @@ our_iterable[1] # TypeError
|
||||
# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft.
|
||||
our_iterator = iter(our_iterable)
|
||||
|
||||
# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es geraden hat während wir durch es gehen.
|
||||
# Das jeweeils nächste Objekt bekommen wir mit "next()"
|
||||
# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen.
|
||||
# Das jeweils nächste Objekt bekommen wir mit "next()"
|
||||
next(our_iterator) #=> "one"
|
||||
|
||||
# Es hält den vorherigen Status
|
||||
@ -442,7 +442,7 @@ def keyword_args(**kwargs):
|
||||
# Rufen wir es mal auf, um zu sehen, was passiert
|
||||
keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
|
||||
|
||||
# Wir können beides gleichzeitig machem, wenn wir wollen
|
||||
# Wir können beides gleichzeitig machen, wenn wir wollen
|
||||
def all_the_args(*args, **kwargs):
|
||||
print(args)
|
||||
print(kwargs)
|
||||
|
119
de-de/rst-de.html.markdown
Normal file
119
de-de/rst-de.html.markdown
Normal file
@ -0,0 +1,119 @@
|
||||
---
|
||||
language: restructured text (RST)
|
||||
filename: restructuredtext.rst
|
||||
contributors:
|
||||
- ["DamienVGN", "https://github.com/martin-damien"]
|
||||
- ["Andre Polykanine", "https://github.com/Oire"]
|
||||
translators:
|
||||
- ["Dennis Keller", "https://github.com/denniskeller"]
|
||||
lang: de-de
|
||||
---
|
||||
|
||||
RST ist ein Dateiformat, das von der Python Community entwickelt wurde,
|
||||
|
||||
um Dokumentation zu schreiben (und ist somit Teil von Docutils).
|
||||
|
||||
RST-Dateien sind simple Textdateien mit einer leichtgewichtigen Syntax (im Vergleich zu HTML).
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
Um Restructured Text zu vewenden musst du [Python](http://www.python.org)
|
||||
|
||||
installieren und das `docutils` Packet installieren. `docutils` kann mit dem folgenden
|
||||
|
||||
Befehl auf der Kommandozeile installiert werden:
|
||||
|
||||
```bash
|
||||
$ easy_install docutils
|
||||
```
|
||||
|
||||
Wenn auf deinem System `pip` installiert kannst du es statdessen auch verwenden:
|
||||
|
||||
```bash
|
||||
$ pip install docutils
|
||||
```
|
||||
|
||||
|
||||
## Dateisyntax
|
||||
|
||||
Ein einfaches Beispiel für die Dateisyntax:
|
||||
|
||||
```
|
||||
.. Zeilen, die mit zwei Punkten starten sind spezielle Befehle.
|
||||
|
||||
.. Wenn kein Befehl gefunden wird, wird die Zeile als Kommentar gewertet.
|
||||
|
||||
============================================================================
|
||||
Haupttitel werden mit Gleichheitszeichen darüber und darunter gekennzeichnet
|
||||
============================================================================
|
||||
|
||||
Beachte das es genau so viele Gleichheitszeichen, wie Hauptitelzeichen
|
||||
geben muss.
|
||||
|
||||
Titel werden auch mit Gleichheitszeichen unterstrichen
|
||||
======================================================
|
||||
|
||||
Untertitel werden mit Strichen gekennzeichnet
|
||||
---------------------------------------------
|
||||
|
||||
Text in *kursiv* oder in **fett**. Du kannst Text als Code "makieren", wenn
|
||||
du doppelte Backquotes verwendest ``: ``print()``.
|
||||
|
||||
Listen sind so einfach wie in Markdown:
|
||||
|
||||
- Erstes Element
|
||||
- Zweites Element
|
||||
- Unterelement
|
||||
|
||||
oder
|
||||
|
||||
* Erstes Element
|
||||
* Zweites Element
|
||||
* Unterelement
|
||||
|
||||
Tabellen sind einfach zu schreiben:
|
||||
|
||||
=========== ==========
|
||||
Land Hauptstadt
|
||||
=========== ==========
|
||||
Frankreich Paris
|
||||
Japan Tokyo
|
||||
=========== ========
|
||||
|
||||
Komplexere Tabellen (zusammengeführte Spalten und Zeilen) können einfach
|
||||
erstellt werden, aber ich empfehle dir dafür die komplette Dokumentation zu lesen :)
|
||||
|
||||
Es gibt mehrere Möglichkeiten um Links zu machen:
|
||||
|
||||
- Wenn man einen Unterstrich hinter einem Wort hinzufügt: Github_ Zusätzlich
|
||||
muss man die Zielurl nach dem Text hinzufügen.
|
||||
(Dies hat den Vorteil, dass man keine unnötigen Urls in lesbaren Text einfügt.
|
||||
- Wenn man die vollständige Url eingibt : https://github.com/
|
||||
(Dies wird automatisch in ein Link konvertiert.)
|
||||
- Wenn man es mehr Markdown ähnlich eingibt: `Github <https://github.com/>`_ .
|
||||
|
||||
.. _Github https://github.com/
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Wie man es verwendet
|
||||
|
||||
RST kommt mit docutils, dort hast du den Befehl `rst2html`, zum Beispiel:
|
||||
|
||||
```bash
|
||||
$ rst2html myfile.rst output.html
|
||||
```
|
||||
|
||||
*Anmerkung : Auf manchen Systemen könnte es rst2html.py sein*
|
||||
|
||||
Es gibt komplexere Anwendungen, die das RST Format verwenden:
|
||||
|
||||
- [Pelican](http://blog.getpelican.com/), ein statischer Websitengenerator
|
||||
- [Sphinx](http://sphinx-doc.org/), Ein Dokumentationsgenerator
|
||||
- und viele Andere
|
||||
|
||||
## Zum Lesen
|
||||
|
||||
- [Offizielle Schnellreferenz](http://docutils.sourceforge.net/docs/user/rst/quickref.html)
|
330
de-de/shutit-de.html.markdown
Normal file
330
de-de/shutit-de.html.markdown
Normal file
@ -0,0 +1,330 @@
|
||||
---
|
||||
category: tool
|
||||
filename: learnshutit.html
|
||||
tool: ShutIt
|
||||
contributors:
|
||||
- ["Ian Miell", "http://ian.meirionconsulting.tk"]
|
||||
translators:
|
||||
- ["Dennis Keller", "https://github.com/denniskeller"]
|
||||
lang: de-de
|
||||
---
|
||||
|
||||
## ShutIt
|
||||
|
||||
ShuIt ist eine Shellautomationsframework, welches für eine einfache
|
||||
Handhabung entwickelt wurde.
|
||||
|
||||
Er ist ein Wrapper, der auf einem Python expect Klon (pexpect) basiert.
|
||||
|
||||
Es ist damit ein 'expect ohne Schmerzen'.
|
||||
|
||||
Es ist verfügbar als pip install.
|
||||
|
||||
## Hello World
|
||||
|
||||
Starten wir mit dem einfachsten Beispiel. Erstelle eine Datei names example.py
|
||||
|
||||
```python
|
||||
|
||||
import shutit
|
||||
session = shutit.create_session('bash')
|
||||
session.send('echo Hello World', echo=True)
|
||||
```
|
||||
|
||||
Führe es hiermit aus:
|
||||
|
||||
```bash
|
||||
python example.py
|
||||
```
|
||||
|
||||
gibt aus:
|
||||
|
||||
```bash
|
||||
$ python example.py
|
||||
echo "Hello World"
|
||||
echo "Hello World"
|
||||
Hello World
|
||||
Ians-MacBook-Air.local:ORIGIN_ENV:RhuebR2T#
|
||||
```
|
||||
|
||||
Das erste Argument zu 'send' ist der Befehl, den du ausführen möchtest.
|
||||
Das 'echo' Argument gibt die Terminalinteraktion aus. ShuIt ist standardmäßig leise.
|
||||
|
||||
'Send' kümmert sich um die nervige Arbeiten mit den Prompts und macht
|
||||
alles was du von 'expect' erwarten würdest.
|
||||
|
||||
|
||||
## Logge dich auf einen Server ein
|
||||
|
||||
Sagen wir du möchtest dich auf einen Server einloggen und einen Befehl ausführen.
|
||||
Ändere dafür example.py folgendermaßen:
|
||||
|
||||
```python
|
||||
import shutit
|
||||
session = shutit.create_session('bash')
|
||||
session.login('ssh you@example.com', user='du', password='meinpassword')
|
||||
session.send('hostname', echo=True)
|
||||
session.logout()
|
||||
```
|
||||
|
||||
Dies erlaubt dir dich auf deinen Server einzuloggen
|
||||
(ersetze die Details mit deinen Eigenen) und das Programm gibt dir deinen Hostnamen aus.
|
||||
|
||||
```
|
||||
$ python example.py
|
||||
hostname
|
||||
hostname
|
||||
example.com
|
||||
example.com:cgoIsdVv:heDa77HB#
|
||||
```
|
||||
|
||||
|
||||
Es ist klar das das nicht sicher ist. Stattdessen kann man Folgendes machen:
|
||||
|
||||
```python
|
||||
import shutit
|
||||
session = shutit.create_session('bash')
|
||||
password = session.get_input('', ispass=True)
|
||||
session.login('ssh you@example.com', user='du', password=password)
|
||||
session.send('hostname', echo=True)
|
||||
session.logout()
|
||||
```
|
||||
|
||||
Dies zwingt dich dein Passwort einzugeben:
|
||||
|
||||
```
|
||||
$ python example.py
|
||||
Input Secret:
|
||||
hostname
|
||||
hostname
|
||||
example.com
|
||||
example.com:cgoIsdVv:heDa77HB#
|
||||
```
|
||||
|
||||
|
||||
Die 'login' Methode übernimmt wieder das veränderte Prompt für den Login.
|
||||
Du übergibst ShutIt den User und das Passwort, falls es benötigt wird,
|
||||
mit den du dich einloggen möchtest. ShutIt übernimmt den Rest.
|
||||
|
||||
'logout' behandelt das Ende von 'login' und übernimmt alle Veränderungen des
|
||||
Prompts für dich.
|
||||
|
||||
## Einloggen auf mehrere Server
|
||||
|
||||
Sagen wir, dass du eine Serverfarm mit zwei Servern hast und du dich in
|
||||
beide Server einloggen möchtest. Dafür musst du nur zwei Session und
|
||||
Logins erstellen und kannst dann Befehle schicken:
|
||||
|
||||
```python
|
||||
import shutit
|
||||
session1 = shutit.create_session('bash')
|
||||
session2 = shutit.create_session('bash')
|
||||
password1 = session1.get_input('Password für server1', ispass=True)
|
||||
password2 = session2.get_input('Password für server2', ispass=True)
|
||||
session1.login('ssh you@one.example.com', user='du', password=password1)
|
||||
session2.login('ssh you@two.example.com', user='du', password=password2)
|
||||
session1.send('hostname', echo=True)
|
||||
session2.send('hostname', echo=True)
|
||||
session1.logout()
|
||||
session2.logout()
|
||||
```
|
||||
|
||||
Gibt aus:
|
||||
|
||||
```bash
|
||||
$ python example.py
|
||||
Password for server1
|
||||
Input Secret:
|
||||
|
||||
Password for server2
|
||||
Input Secret:
|
||||
hostname
|
||||
hostname
|
||||
one.example.com
|
||||
one.example.com:Fnh2pyFj:qkrsmUNs# hostname
|
||||
hostname
|
||||
two.example.com
|
||||
two.example.com:Gl2lldEo:D3FavQjA#
|
||||
```
|
||||
|
||||
## Beispiel: Überwachen mehrerer Server
|
||||
|
||||
Wir können das obige Programm in ein einfaches Überwachungstool bringen indem
|
||||
wir Logik hinzufügen um die Ausgabe von einem Befehl zu betrachten.
|
||||
|
||||
```python
|
||||
import shutit
|
||||
capacity_command="""df / | awk '{print $5}' | tail -1 | sed s/[^0-9]//"""
|
||||
session1 = shutit.create_session('bash')
|
||||
session2 = shutit.create_session('bash')
|
||||
password1 = session.get_input('Passwort für Server1', ispass=True)
|
||||
password2 = session.get_input('Passwort für Server2', ispass=True)
|
||||
session1.login('ssh you@one.example.com', user='du', password=password1)
|
||||
session2.login('ssh you@two.example.com', user='du', password=password2)
|
||||
capacity = session1.send_and_get_output(capacity_command)
|
||||
if int(capacity) < 10:
|
||||
print(kein Platz mehr auf Server1!')
|
||||
capacity = session2.send_and_get_output(capacity_command)
|
||||
if int(capacity) < 10:
|
||||
print(kein Platz mehr auf Server2!')
|
||||
session1.logout()
|
||||
session2.logout()
|
||||
```
|
||||
|
||||
Hier kannst du die 'send\_and\_get\_output' Methode verwenden um die Ausgabe von dem
|
||||
Kapazitätsbefehl (df) zu erhalten.
|
||||
|
||||
Es gibt elegantere Wege als oben (z.B. kannst du ein Dictionary verwenden um über
|
||||
die Server zu iterieren), aber es hängt and dir wie clever das Python sein muss.
|
||||
|
||||
|
||||
## kompliziertere IO - Expecting
|
||||
|
||||
Sagen wir du hast eine Interaktion mit einer interaktiven Kommandozeilenprogramm,
|
||||
die du automatisieren möchtest. Hier werden wir Telnet als triviales Beispiel verwenden:
|
||||
|
||||
```python
|
||||
import shutit
|
||||
session = shutit.create_session('bash')
|
||||
session.send('telnet', expect='elnet>', echo=True)
|
||||
session.send('open google.com 80', expect='scape character', echo=True)
|
||||
session.send('GET /', echo=True, check_exit=False)
|
||||
session.logout()
|
||||
```
|
||||
|
||||
Beachte das 'expect' Argument. Du brauchst nur ein Subset von Telnets
|
||||
Eingabeaufforderung um es abzugleichen und fortzufahren.
|
||||
|
||||
Beachte auch das neue Argument 'check\_exit'. Wir werden nachher nochmal
|
||||
darauf zurückkommen. Die Ausgabe von oben ist:
|
||||
|
||||
```bash
|
||||
$ python example.py
|
||||
telnet
|
||||
telnet> open google.com 80
|
||||
Trying 216.58.214.14...
|
||||
Connected to google.com.
|
||||
Escape character is '^]'.
|
||||
GET /
|
||||
HTTP/1.0 302 Found
|
||||
Cache-Control: private
|
||||
Content-Type: text/html; charset=UTF-8
|
||||
Referrer-Policy: no-referrer
|
||||
Location: http://www.google.co.uk/?gfe_rd=cr&ei=huczWcj3GfTW8gfq0paQDA
|
||||
Content-Length: 261
|
||||
Date: Sun, 04 Jun 2017 10:57:10 GMT
|
||||
|
||||
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
|
||||
<TITLE>302 Moved</TITLE></HEAD><BODY>
|
||||
<H1>302 Moved</H1>
|
||||
The document has moved
|
||||
<A HREF="http://www.google.co.uk/?gfe_rd=cr&ei=huczWcj3GfTW8gfq0paQDA">
|
||||
here
|
||||
</A>.
|
||||
</BODY></HTML>
|
||||
Connection closed by foreign host.
|
||||
```
|
||||
|
||||
Nun zurück zu 'check\_exit=False'. Da das Telnet Programm einen Fehler mit
|
||||
Fehlercode (1) zurückgibt und wir nicht möchten das das Skript fehlschlägt
|
||||
kannst du 'check\_exit=False' setzen und damit ShuIt wissen lassen, dass
|
||||
der Ausgabecode dich nicht interessiert.
|
||||
|
||||
Wenn du das Argument nicht mitgegeben hättest, dann hätte dir ShutIt
|
||||
ein interaktives Terminal zurückgegeben, falls es ein Terminal zum
|
||||
kommunizieren gibt. Dies nennt sich ein 'Pause point'.
|
||||
|
||||
|
||||
## Pause Points
|
||||
|
||||
Du kannst jederzeit 'pause point' auslösen, wenn du Folgendes in deinem Skript aufrufst:
|
||||
|
||||
```python
|
||||
[...]
|
||||
session.pause_point('Das ist ein pause point')
|
||||
[...]
|
||||
```
|
||||
|
||||
Danach kannst du das Skript fortführen, wenn du CTRL und ']' zur selben Zeit drückst.
|
||||
Dies ist gut für Debugging: Füge ein Pause Point hinzu und schaue dich um.
|
||||
Danach kannst du das Programm weiter ausführen. Probiere folgendes aus:
|
||||
|
||||
```python
|
||||
import shutit
|
||||
session = shutit.create_session('bash')
|
||||
session.pause_point('Schaue dich um!')
|
||||
session.send('echo "Hat dir der Pause point gefallen?"', echo=True)
|
||||
```
|
||||
|
||||
Dies würde folgendes ausgeben:
|
||||
|
||||
```bash
|
||||
$ python example.py
|
||||
Schaue dich um!
|
||||
|
||||
Ians-Air.home:ORIGIN_ENV:I00LA1Mq# bash
|
||||
imiell@Ians-Air:/space/git/shutit ⑂ master +
|
||||
CTRL-] caught, continuing with run...
|
||||
2017-06-05 15:12:33,577 INFO: Sending: exit
|
||||
2017-06-05 15:12:33,633 INFO: Output (squashed): exitexitIans-Air.home:ORIGIN_ENV:I00LA1Mq# [...]
|
||||
echo "Hat dir der Pause point gefallen?"
|
||||
echo "Hat dir der Pause point gefallen?"
|
||||
Hat dir der Pause point gefallen?
|
||||
Ians-Air.home:ORIGIN_ENV:I00LA1Mq#
|
||||
```
|
||||
|
||||
|
||||
## noch kompliziertere IO - Hintergrund
|
||||
|
||||
Kehren wir zu unseren Beispiel mit dem Überwachen von mehreren Servern zurück.
|
||||
Stellen wir uns vor, dass wir eine langlaufende Aufgabe auf jedem Server durchführen möchten.
|
||||
Standardmäßig arbeitet ShutIt seriell, was sehr lange dauern würde.
|
||||
Wir können jedoch die Aufgaben im Hintergrund laufen lassen um sie zu beschleunigen.
|
||||
|
||||
Hier ist ein Beispiel, welches du ausprobieren kannst.
|
||||
Es verwendet den trivialen Befehl: 'sleep'.
|
||||
|
||||
|
||||
```python
|
||||
import shutit
|
||||
import time
|
||||
long_command="""sleep 60"""
|
||||
session1 = shutit.create_session('bash')
|
||||
session2 = shutit.create_session('bash')
|
||||
password1 = session1.get_input('Password for server1', ispass=True)
|
||||
password2 = session2.get_input('Password for server2', ispass=True)
|
||||
session1.login('ssh you@one.example.com', user='du', password=password1)
|
||||
session2.login('ssh you@two.example.com', user='du', password=password2)
|
||||
start = time.time()
|
||||
session1.send(long_command, background=True)
|
||||
session2.send(long_command, background=True)
|
||||
print('Es hat: ' + str(time.time() - start) + ' Sekunden zum Starten gebraucht')
|
||||
session1.wait()
|
||||
session2.wait()
|
||||
print('Es hat:' + str(time.time() - start) + ' Sekunden zum Vollenden gebraucht')
|
||||
```
|
||||
|
||||
Mein Computer meint, dass er 0.5 Sekunden gebraucht hat um die Befehle zu starten
|
||||
und dann nur etwas über eine Minute gebraucht um sie zu beenden
|
||||
(mit Verwendung der 'wait' Methode).
|
||||
|
||||
|
||||
Das alles ist trivial, aber stelle dir vor das du hunderte an Servern so managen
|
||||
kannst und man kann nun das Potential sehen, die in ein paar Zeilen Code und ein Python
|
||||
import liegen können.
|
||||
|
||||
|
||||
## Lerne mehr
|
||||
|
||||
Es gibt noch viel mehr, was mit ShutIt erreicht werden kann.
|
||||
|
||||
Um mehr zu erfahren, siehe:
|
||||
|
||||
[ShutIt](https://ianmiell.github.io/shutit/)
|
||||
[GitHub](https://github.com/ianmiell/shutit/blob/master/README.md)
|
||||
|
||||
Es handelt sich um ein breiteres Automatiesierungsframework, und das oben
|
||||
genannte ist der sogennante 'standalone Modus'.
|
||||
|
||||
Feedback, feature requests, 'Wie mache ich es' sind herzlich willkommen! Erreiche mit unter
|
||||
[@ianmiell](https://twitter.com/ianmiell)
|
@ -42,9 +42,9 @@ for i=0 to n-1
|
||||
|
||||
### Some Famous DP Problems
|
||||
|
||||
- Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
|
||||
- Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
|
||||
- Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
|
||||
- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]()
|
||||
- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]()
|
||||
- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]()
|
||||
|
||||
## Online Resources
|
||||
|
||||
|
@ -287,7 +287,11 @@ end
|
||||
PrivateMath.sum(1, 2) #=> 3
|
||||
# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
|
||||
|
||||
# Function declarations also support guards and multiple clauses:
|
||||
# Function declarations also support guards and multiple clauses.
|
||||
# When a function with multiple clauses is called, the first function
|
||||
# that satisfies the clause will be invoked.
|
||||
# Example: invoking area({:circle, 3}) will call the second area
|
||||
# function defined below, not the first:
|
||||
defmodule Geometry do
|
||||
def area({:rectangle, w, h}) do
|
||||
w * h
|
||||
|
@ -72,8 +72,8 @@ List.head [] -- Nothing
|
||||
|
||||
-- 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
|
||||
Tuple.first ("elm", 42) -- "elm"
|
||||
Tuple.second ("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".
|
||||
|
@ -166,7 +166,7 @@ function arithmetic_functions(a, b, c, localvar) {
|
||||
# trigonométricas estándar
|
||||
localvar = sin(a)
|
||||
localvar = cos(a)
|
||||
localvar = atan2(a, b) # arcotangente de b / a
|
||||
localvar = atan2(b, a) # arcotangente de b / a
|
||||
|
||||
# Y cosas logarítmicas
|
||||
localvar = exp(a)
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: Brainfuck
|
||||
filename: brainfuck-es.bf
|
||||
language: bf
|
||||
filename: bf-es.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
- ["Mathias Bynens", "http://mathiasbynens.be/"]
|
||||
|
@ -823,7 +823,6 @@ v.swap(vector<Foo>());
|
||||
```
|
||||
Otras lecturas:
|
||||
|
||||
Una referencia del lenguaje hasta a la fecha se puede encontrar en
|
||||
<http://cppreference.com/w/cpp>
|
||||
|
||||
Recursos adicionales se pueden encontrar en <http://cplusplus.com>
|
||||
* Una referencia del lenguaje hasta a la fecha se puede encontrar en [CPP Reference](http://cppreference.com/w/cpp).
|
||||
* Recursos adicionales se pueden encontrar en [[CPlusPlus]](http://cplusplus.com).
|
||||
* Un tutorial que cubre los conceptos básicos del lenguaje y la configuración del entorno de codificación está disponible en [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FF).
|
||||
|
@ -5,7 +5,7 @@ contributors:
|
||||
- ["Irfan Charania", "https://github.com/irfancharania"]
|
||||
- ["Max Yankov", "https://github.com/golergka"]
|
||||
translators:
|
||||
- ["Olfran Jiménez", "https://twitter.com/neslux"]
|
||||
- ["Olfran Jiménez", "https://twitter.com/neslux"]
|
||||
lang: es-es
|
||||
|
||||
---
|
||||
|
293
es-es/erlang-es.html.markdown
Normal file
293
es-es/erlang-es.html.markdown
Normal file
@ -0,0 +1,293 @@
|
||||
---
|
||||
language: erlang
|
||||
lang: es-es
|
||||
contributors:
|
||||
- ["Giovanni Cappellotto", "http://www.focustheweb.com/"]
|
||||
translators:
|
||||
- ["Ernesto Pelayo", "http://github.com/ErnestoPelayo"]
|
||||
filename: learnerlang-es.erl
|
||||
---
|
||||
|
||||
# Erlang
|
||||
% Signo de porcentaje inicia un comentario de una línea.
|
||||
|
||||
%% Se usarán dos por ciento de caracteres para comentar funciones.
|
||||
|
||||
%%% Se usarán tres por ciento de caracteres para comentar los módulos.
|
||||
|
||||
### Utilizamos tres tipos de puntuación en Erlang.
|
||||
|
||||
+ **Comas (`,`)** argumentos separados en llamadas a funciones, constructores de
|
||||
datos y patrones.
|
||||
|
||||
+ **Periodos (`.`)** (seguido de espacios en blanco) separa funciones completas y
|
||||
expresiones en el shell.
|
||||
|
||||
+ **Semicolons (`;`)** cláusulas separadas. Encontramos cláusulas en varios contextos: de definiciones de funciones y en **`case`**,**` if`**, **`try..catch`**, y **` receive`** de expresiones.
|
||||
|
||||
## 1.-Variables y coincidencia de patrones.
|
||||
|
||||
|
||||
- En Erlang, las nuevas variables están vinculadas con una instrucción **`=`**.
|
||||
>**Num = 42.**
|
||||
|
||||
- Todos los nombres de variables deben comenzar con una letra mayúscula.
|
||||
|
||||
- Erlang tiene variables de asignación única; si intentas asignar un diferente de valor a la variable **`Num`**, obtendrá un error.
|
||||
Num = 43. **error de excepción**: no coincide con el valor del lado derecho 43
|
||||
|
||||
- En la mayoría de los idiomas, **`=`** denota una declaración de asignación. En Erlang, sin embargo,**`=`** denota una operación de coincidencia de patrones.
|
||||
|
||||
- Cuando se usa una variable vacía en el del lado izquierdo del operador `=` to está vinculado (asignado), pero cuando está atado variable se usa en el lado izquierdo, se observa el siguiente comportamiento.
|
||||
>**`Lhs = Rhs`** realmente significa esto: evaluar el lado derecho (**` Rhs`**), y luego coincide con el resultado contra el patrón en el lado izquierdo (**`Lhs`**).
|
||||
>**Num = 7 * 6.**
|
||||
|
||||
- Número de punto flotante.
|
||||
Pi = 3.14159.
|
||||
|
||||
- Los átomos se usan para representar diferentes valores constantes no numéricos.
|
||||
|
||||
- Átomos comienza con letras minúsculas, seguido de una secuencia de caracteres
|
||||
|
||||
- alfanuméricos de caracteres o el signo de subrayado (**`_`**) o en (**` @ `**).
|
||||
>**Hola = hola.**
|
||||
**OtherNode = ejemplo @ nodo.**
|
||||
|
||||
- Los átomos con valores no alfanuméricos se pueden escribir al encerrar los átomos con apóstrofes.
|
||||
>**AtomWithSpace = 'algún átomo con espacio'.**
|
||||
|
||||
+ Tuples son similares a las estructuras en C.
|
||||
>**Point = {point, 10, 45}.**
|
||||
|
||||
- Si queremos extraer algunos valores de una tupla, usamos el patrón de coincidencia
|
||||
operador **`=`**.
|
||||
> **{punto, X, Y} = Punto. % X = 10, Y = 45**
|
||||
|
||||
- Podemos usar **`_`** como marcador de posición para variables que no nos interesan.
|
||||
|
||||
- El símbolo **`_`** se llama una variable anónima. A diferencia de las variables regulares,varias apariciones de `_` en el mismo patrón no tienen que vincularse a mismo valor.
|
||||
>**Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}.**
|
||||
**{_, {_, {_, who }, _}, _} = Persona. % Who = joe**
|
||||
|
||||
+ Creamos una lista al encerrar los elementos de la lista entre corchetes y separándolos con comas.
|
||||
|
||||
+ Los elementos individuales de una lista pueden ser de cualquier tipo.
|
||||
|
||||
- El primer elemento de una lista es el encabezado de la lista. Si te imaginas eliminar del encabezado de la lista, lo que queda se llama cola de la lista.
|
||||
>**ThingsToBuy = [{manzanas, 10}, {peras, 6}, {leche, 3}].**
|
||||
|
||||
- Si `T` es una lista, entonces **` [H | T] `** también es una lista, con la cabeza **` H`** y la cola **`T`**.
|
||||
|
||||
+ La barra vertical (**`|`**) separa el encabezado de una lista de su cola.
|
||||
**`[]`** es la lista vacía.
|
||||
|
||||
+ Podemos extraer elementos de una lista con una operación de coincidencia de
|
||||
patrones. Si nosotros tiene una lista no vacía **`L`**, luego la expresión **` [X | Y] = L`**, donde **`X`** y **` Y`** son variables independientes, extraerán el encabezado de la lista en **`X`** y la cola de la lista en **`Y`**.
|
||||
>**[FirstThing | OtherThingsToBuy] = ThingsToBuy.**
|
||||
**FirstThing = {manzanas, 10}**
|
||||
**OtherThingsToBuy = [{peras, 6}, {leche, 3}]**
|
||||
|
||||
+ No hay cadenas en Erlang. Las cadenas son realmente solo listas de enteros.
|
||||
|
||||
+ Las cadenas están entre comillas dobles (**`" `**).
|
||||
>**Nombre = "Hola".
|
||||
[72, 101, 108, 108, 111] = "Hola".**
|
||||
|
||||
## 2. Programación secuencial.
|
||||
|
||||
|
||||
- Los módulos son la unidad básica de código en Erlang. Todas las funciones que escribimos son almacenado en módulos.
|
||||
|
||||
- Los módulos se almacenan en archivos con extensiones **`.erl`**.
|
||||
- Los módulos deben compilarse antes de poder ejecutar el código. Un módulo compilado tiene el extensión **`.beam`**.
|
||||
>**-módulo (geometría).
|
||||
-export ([area / 1]). de la lista de funciones exportadas desde el módulo.**
|
||||
|
||||
+ La función **`área`** consta de dos cláusulas. Las cláusulas están separadas por un punto y coma, y la cláusula final termina con punto-espacio en blanco. Cada cláusula tiene una cabeza y un cuerpo; la cabeza consiste en un nombre de función seguido de un patrón (entre paréntesis), y el cuerpo consiste en una secuencia de expresiones, que se evalúan si el patrón en la cabeza es exitoso coincide con los argumentos de llamada. Los patrones se combinan en el orden aparecen en la definición de la función.
|
||||
>**área ({rectángulo, ancho, Ht}) -> ancho * Ht;
|
||||
área ({círculo, R}) -> 3.14159 * R * R** .
|
||||
|
||||
### Compila el código en el archivo geometry.erl.
|
||||
c (geometría). {ok, geometría}
|
||||
|
||||
+ Necesitamos incluir el nombre del módulo junto con el nombre de la función para identifica exactamente qué función queremos llamar.
|
||||
>**geometría: área ({rectángulo, 10, 5}). % 50**
|
||||
**geometría: área ({círculo, 1.4}). % 6.15752**
|
||||
|
||||
+ En Erlang, dos funciones con el mismo nombre y arity diferente (número de argumentos) en el mismo módulo representan funciones completamente diferentes.
|
||||
>-**module (lib_misc)**.
|
||||
-**export ([sum / 1])**.
|
||||
|
||||
- función de exportación **`suma`** de arity 1 acepta un argumento:
|
||||
>**lista de enteros.
|
||||
suma (L) -> suma (L, 0).
|
||||
suma ([], N) -> N;
|
||||
suma ([H | T], N) -> suma (T, H + N).**
|
||||
+ Funs son funciones **"anónimas"**. Se llaman así porque tienen sin nombre. Sin embargo, pueden asignarse a variables.
|
||||
Doble = diversión (X) -> 2 * X final. **`Doble`** apunta a una función anónima con el controlador: **#Fun <erl_eval.6.17052888>
|
||||
Doble (2). % 4**
|
||||
|
||||
- Functions acepta funs como sus argumentos y puede devolver funs.
|
||||
>**Mult = diversión (Times) -> (fun (X) -> X * Times end) end.
|
||||
Triple = Mult (3).
|
||||
Triple (5). % 15**
|
||||
|
||||
- Las listas de comprensión son expresiones que crean listas sin tener que usar
|
||||
funs, mapas o filtros.
|
||||
- La notación **`[F (X) || X <- L] `** significa" la lista de **`F (X)`** donde se toma **`X`**% de la lista **`L`."**
|
||||
>**L = [1,2,3,4,5].
|
||||
[2 * X || X <- L]. % [2,4,6,8,10]**
|
||||
|
||||
- Una lista de comprensión puede tener generadores y filtros, que seleccionan un subconjunto de los valores generados
|
||||
>**EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4]**
|
||||
|
||||
- Los protectores son construcciones que podemos usar para aumentar el poder del patrón coincidencia. Usando guardias, podemos realizar pruebas simples y comparaciones en el de variables en un patrón.
|
||||
Puede usar guardias en la cabeza de las definiciones de funciones donde están introducido por la palabra clave **`when`**, o puede usarlos en cualquier lugar del lenguaje donde se permite una expresión.
|
||||
>**max (X, Y) cuando X> Y -> X;
|
||||
max (X, Y) -> Y.**
|
||||
|
||||
- Un guardia es una serie de expresiones de guardia, separadas por comas (**`,`**).
|
||||
- La guardia **`GuardExpr1, GuardExpr2, ..., GuardExprN`** es verdadera si todos los guardias expresiones **`GuardExpr1`,` GuardExpr2`, ..., `GuardExprN`** evalúan **`true`**.
|
||||
>**is_cat (A) cuando is_atom (A), A =: = cat -> true;
|
||||
is_cat (A) -> false.
|
||||
is_dog (A) cuando is_atom (A), A =: = dog -> true;
|
||||
is_dog (A) -> false.**
|
||||
|
||||
No nos detendremos en el operador **`=: =`** aquí; Solo tenga en cuenta que está acostumbrado a comprueba si dos expresiones de Erlang tienen el mismo valor * y * del mismo tipo. Contrasta este comportamiento con el del operador **`==`**:
|
||||
|
||||
>**1 + 2 =: = 3.% true
|
||||
1 + 2 =: = 3.0. % false
|
||||
1 + 2 == 3.0. % true**
|
||||
|
||||
Una secuencia de guardia es una guardia individual o una serie de guardias, separadas por punto y coma (**`;`**). La secuencia de guardia **`G1; G2; ...; Gn`** es verdadero si en menos uno de los guardias **`G1`,` G2`, ..., `Gn`** se evalúa como **` true`**.
|
||||
>**is_pet (A) cuando is_atom (A), (A =: = dog); (A =: = cat) -> true;
|
||||
is_pet (A) -> false.**
|
||||
|
||||
- **Advertencia**: no todas las expresiones de Erlang válidas se pueden usar como expresiones de guarda; en particular, nuestras funciones **`is_cat`** y **`is_dog`** no se pueden usar dentro del secuencia de protección en la definición de **`is_pet`**. Para una descripción de expresiones permitidas en secuencias de guarda, consulte la sección específica en el manual de referencia de Erlang:
|
||||
### http://erlang.org/doc/reference_manual/expressions.html#guards
|
||||
|
||||
- Los registros proporcionan un método para asociar un nombre con un elemento particular en un de tupla De las definiciones de registros se pueden incluir en los archivos de código fuente de Erlang o poner en archivos con la extensión **`.hrl`**, que luego están incluidos en el código fuente de Erlang de archivos.
|
||||
|
||||
>**-record (todo, {
|
||||
status = recordatorio,% valor predeterminado
|
||||
quien = joe,
|
||||
texto
|
||||
}).**
|
||||
|
||||
- Tenemos que leer las definiciones de registro en el shell antes de que podamos definir un
|
||||
de registro. Usamos la función shell **`rr`** (abreviatura de los registros de lectura) para hacer esto.
|
||||
|
||||
>**rr ("records.hrl").** % [que hacer]
|
||||
|
||||
- **Creando y actualizando registros:**
|
||||
>**X = #todo {}.
|
||||
% #todo {status = recordatorio, who = joe, text = undefined}
|
||||
X1 = #todo {estado = urgente, texto = "Corregir errata en el libro"}.
|
||||
% #todo {status = urgent, who = joe, text = "Corregir errata en el libro"}
|
||||
X2 = X1 # todo {estado = hecho}.
|
||||
% #todo {status = done, who = joe, text = "Corregir errata en el libro"}
|
||||
expresiones `case`**.
|
||||
|
||||
**`filter`** devuelve una lista de todos los elementos **` X`** en una lista **`L`** para la cual **` P (X) `** es true.
|
||||
>**filter(P, [H|T]) ->
|
||||
case P(H) of
|
||||
true -> [H|filter(P, T)];
|
||||
false -> filter(P, T)
|
||||
end;
|
||||
filter(P, []) -> [].
|
||||
filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4]**
|
||||
|
||||
expresiones **`if`**.
|
||||
>**max(X, Y) ->
|
||||
if
|
||||
X > Y -> X;
|
||||
X < Y -> Y;
|
||||
true -> nil
|
||||
end.**
|
||||
|
||||
**Advertencia:** al menos uno de los guardias en la expresión **`if`** debe evaluar a **`true`**; de lo contrario, se generará una excepción.
|
||||
|
||||
## 3. Excepciones.
|
||||
|
||||
|
||||
- El sistema genera excepciones cuando se encuentran errores internos o explícitamente en el código llamando **`throw (Exception)`**, **`exit (Exception)`**, o **`erlang: error (Exception)`**.
|
||||
>**generate_exception (1) -> a;
|
||||
generate_exception (2) -> throw (a);
|
||||
generate_exception (3) -> exit (a);
|
||||
generate_exception (4) -> {'EXIT', a};
|
||||
generate_exception (5) -> erlang: error (a).**
|
||||
|
||||
- Erlang tiene dos métodos para atrapar una excepción. Una es encerrar la llamada a de la función que genera la excepción dentro de una expresión **`try ... catch`**.
|
||||
>**receptor (N) ->
|
||||
prueba generar_excepción (N) de
|
||||
Val -> {N, normal, Val}
|
||||
captura
|
||||
throw: X -> {N, atrapado, arrojado, X};
|
||||
exit: X -> {N, atrapado, salido, X};
|
||||
error: X -> {N, atrapado, error, X}
|
||||
end.**
|
||||
|
||||
- El otro es encerrar la llamada en una expresión **`catch`**. Cuando atrapas un de excepción, se convierte en una tupla que describe el error.
|
||||
>**catcher (N) -> catch generate_exception (N).**
|
||||
|
||||
## 4. Concurrencia
|
||||
|
||||
- Erlang se basa en el modelo de actor para concurrencia. Todo lo que necesitamos para escribir de programas simultáneos en Erlang son tres primitivos: procesos de desove, de envío de mensajes y recepción de mensajes.
|
||||
|
||||
- Para comenzar un nuevo proceso, usamos la función **`spawn`**, que toma una función como argumento.
|
||||
|
||||
>**F = diversión () -> 2 + 2 final. % #Fun <erl_eval.20.67289768>
|
||||
spawn (F). % <0.44.0>**
|
||||
|
||||
- **`spawn`** devuelve un pid (identificador de proceso); puedes usar este pid para enviar de mensajes al proceso. Para pasar mensajes, usamos el operador **`!`**.
|
||||
|
||||
- Para que todo esto sea útil, debemos poder recibir mensajes. Esto es logrado con el mecanismo **`receive`**:
|
||||
|
||||
>**-module (calcular Geometría).
|
||||
-compile (export_all).
|
||||
calculateArea () ->
|
||||
recibir
|
||||
{rectángulo, W, H} ->
|
||||
W * H;
|
||||
{circle, R} ->
|
||||
3.14 * R * R;
|
||||
_ ->
|
||||
io: format ("Solo podemos calcular el área de rectángulos o círculos")
|
||||
end.**
|
||||
|
||||
- Compile el módulo y cree un proceso que evalúe **`calculateArea`** en cáscara.
|
||||
>**c (calcular Geometría).
|
||||
CalculateArea = spawn (calcular Geometría, calcular Área, []).
|
||||
CalculateArea! {círculo, 2}. % 12.56000000000000049738**
|
||||
|
||||
- El shell también es un proceso; puedes usar **`self`** para obtener el pid actual.
|
||||
**self(). % <0.41.0>**
|
||||
|
||||
## 5. Prueba con EUnit
|
||||
|
||||
- Las pruebas unitarias se pueden escribir utilizando los generadores de prueba de EUnits y afirmar macros
|
||||
>**-módulo (fib).
|
||||
-export ([fib / 1]).
|
||||
-include_lib ("eunit / include / eunit.hrl").**
|
||||
|
||||
>**fib (0) -> 1;
|
||||
fib (1) -> 1;
|
||||
fib (N) when N> 1 -> fib (N-1) + fib (N-2).**
|
||||
|
||||
>**fib_test_ () ->
|
||||
[? _assert (fib (0) =: = 1),
|
||||
? _assert (fib (1) =: = 1),
|
||||
? _assert (fib (2) =: = 2),
|
||||
? _assert (fib (3) =: = 3),
|
||||
? _assert (fib (4) =: = 5),
|
||||
? _assert (fib (5) =: = 8),
|
||||
? _assertException (error, function_clause, fib (-1)),
|
||||
? _assert (fib (31) =: = 2178309)
|
||||
]**
|
||||
|
||||
- EUnit exportará automáticamente a una función de prueba () para permitir la ejecución de las pruebas en el shell Erlang
|
||||
fib: test ()
|
||||
|
||||
- La popular barra de herramientas de construcción de Erlang también es compatible con EUnit
|
||||
**`` ` de la unidad de barras de refuerzo
|
||||
``**
|
629
es-es/fsharp-es.html.markdown
Normal file
629
es-es/fsharp-es.html.markdown
Normal file
@ -0,0 +1,629 @@
|
||||
---
|
||||
language: F#
|
||||
lang: es-es
|
||||
contributors:
|
||||
- ['Scott Wlaschin', 'http://fsharpforfunandprofit.com/']
|
||||
translators:
|
||||
- ['Angel Arciniega', 'https://github.com/AngelsProjects']
|
||||
filename: learnfsharp-es.fs
|
||||
---
|
||||
|
||||
F# es un lenguaje de programación funcional y orientado a objetos. Es gratis y su código fuente está abierto. Se ejecuta en Linux, Mac, Windows y más.
|
||||
|
||||
Tiene un poderoso sistema de tipado que atrapa muchos errores de tiempo de compilación, pero usa inferencias de tipados que le permiten ser leídos como un lenguaje dinámico.
|
||||
|
||||
La sintaxis de F# es diferente de los lenguajes que heredan de C.
|
||||
|
||||
- Las llaves no se usan para delimitar bloques de código. En cambio, se usa sangría (como en Python).
|
||||
- Los espacios se usan para separar parámetros en lugar de comas.
|
||||
|
||||
Si quiere probar el siguiente código, puede ir a [tryfsharp.org](http://www.tryfsharp.org/Create) y pegarlo en [REPL](https://es.wikipedia.org/wiki/REPL).
|
||||
|
||||
```fsharp
|
||||
// Los comentarios de una línea se escibren con una doble diagonal
|
||||
(* Los comentarios multilínea usan parentesis (* . . . *)
|
||||
|
||||
-final del comentario multilínea- *)
|
||||
|
||||
// ================================================
|
||||
// Syntaxis básica
|
||||
// ================================================
|
||||
|
||||
// ------ "Variables" (pero no realmente) ------
|
||||
// La palabra reservada "let" define un valor (inmutable)
|
||||
let miEntero = 5
|
||||
let miFlotante = 3.14
|
||||
let miCadena = "hola" // Tenga en cuenta que no es necesario ningún tipado
|
||||
|
||||
// ------ Listas ------
|
||||
let dosACinco = [2;3;4;5] // Los corchetes crean una lista con
|
||||
// punto y coma para delimitadores.
|
||||
let unoACinco = 1 :: dosACinco // :: Crea una lista con un nuevo elemento
|
||||
// El resultado es [1;2;3;4;5]
|
||||
let ceroACinco = [0;1] @ dosACinco // @ Concatena dos listas
|
||||
|
||||
// IMPORTANTE: las comas no se usan para delimitar,
|
||||
// solo punto y coma !
|
||||
|
||||
// ------ Funciones ------
|
||||
// La palabra reservada "let" también define el nombre de una función.
|
||||
let cuadrado x = x * x // Tenga en cuenta que no se usa paréntesis.
|
||||
cuadrado 3 // Ahora, ejecutemos la función.
|
||||
// De nuevo, sin paréntesis.
|
||||
|
||||
let agregar x y = x + y // ¡No use add (x, y)! Eso significa
|
||||
// algo completamente diferente.
|
||||
agregar 2 3 // Ahora, ejecutemos la función.
|
||||
|
||||
// Para definir una función en varias líneas, usemos la sangría.
|
||||
// Los puntos y coma no son necesarios.
|
||||
let pares lista =
|
||||
let esPar x = x%2 = 0 // Establece "esPar" como una función anidada
|
||||
List.filter esPar lista // List.filter es una función de la biblioteca
|
||||
// dos parámetros: una función que devuelve un
|
||||
// booleano y una lista en la que trabajar
|
||||
|
||||
pares unoACinco // Ahora, ejecutemos la función.
|
||||
|
||||
// Puedes usar paréntesis para aclarar.
|
||||
// En este ejemplo, "map" se ejecuta primero, con dos argumentos,
|
||||
// entonces "sum" se ejecuta en el resultado.
|
||||
// Sin los paréntesis, "List.map" se pasará como argumento a List.sum.
|
||||
let sumaDeCuadradosHasta100 =
|
||||
List.sum ( List.map cuadrado [1..100] )
|
||||
|
||||
// Puedes redirigir la salida de una función a otra con "|>"
|
||||
// Redirigir datos es muy común en F#, como con los pipes de UNIX.
|
||||
|
||||
// Aquí está la misma función sumOfSquares escrita usando pipes
|
||||
let sumaDeCuadradosHasta100piped =
|
||||
[1..100] |> List.map cuadrado |> List.sum // "cuadrado" se declara antes
|
||||
|
||||
// Puede definir lambdas (funciones anónimas) gracias a la palabra clave "fun"
|
||||
let sumaDeCuadradosHasta100ConFuncion =
|
||||
[1..100] |> List.map (fun x -> x*x) |> List.sum
|
||||
|
||||
// En F#, no hay palabra clave "return". Una función siempre regresa
|
||||
// el valor de la última expresión utilizada.
|
||||
|
||||
// ------ Coincidencia de patrones ------
|
||||
// Match..with .. es una sobrecarga de la condición de case/ switch.
|
||||
let coincidenciaDePatronSimple =
|
||||
let x = "a"
|
||||
match x with
|
||||
| "a" -> printfn "x es a"
|
||||
| "b" -> printfn "x es b"
|
||||
| _ -> printfn "x es algo mas" // guion bajo corresponde con todos los demás
|
||||
|
||||
// F# no permite valores nulos por defecto - debe usar el tipado de Option
|
||||
// y luego coincide con el patrón.
|
||||
// Some(..) y None son aproximadamente análogos a los envoltorios Nullable
|
||||
let valorValido = Some(99)
|
||||
let valorInvalido = None
|
||||
|
||||
// En este ejemplo, match..with encuentra una coincidencia con "Some" y "None",
|
||||
// y muestra el valor de "Some" al mismo tiempo.
|
||||
let coincidenciaDePatronDeOpciones entrada =
|
||||
match entrada with
|
||||
| Some i -> printfn "la entrada es un int=%d" i
|
||||
| None -> printfn "entrada faltante"
|
||||
|
||||
coincidenciaDePatronDeOpciones validValue
|
||||
coincidenciaDePatronDeOpciones invalidValue
|
||||
|
||||
// ------ Viendo ------
|
||||
// Las funciones printf/printfn son similares a las funciones
|
||||
// Console.Write/WriteLine de C#.
|
||||
printfn "Imprimiendo un int %i, a float %f, a bool %b" 1 2.0 true
|
||||
printfn "Un string %s, y algo generico %A" "hola" [1;2;3;4]
|
||||
|
||||
// También hay funciones printf/sprintfn para formatear datos
|
||||
// en cadena. Es similar al String.Format de C#.
|
||||
|
||||
// ================================================
|
||||
// Mas sobre funciones
|
||||
// ================================================
|
||||
|
||||
// F# es un verdadero lenguaje funcional - las funciones son
|
||||
// entidades de primer nivel y se pueden combinar fácilmente
|
||||
// para crear construcciones poderosas
|
||||
|
||||
// Los módulos se utilizan para agrupar funciones juntas.
|
||||
// Se requiere sangría para cada módulo anidado.
|
||||
module EjemploDeFuncion =
|
||||
|
||||
// define una función de suma simple
|
||||
let agregar x y = x + y
|
||||
|
||||
// uso básico de una función
|
||||
let a = agregar 1 2
|
||||
printfn "1+2 = %i" a
|
||||
|
||||
// aplicación parcial para "hornear en" los parámetros (?)
|
||||
let agregar42 = agregar 42
|
||||
let b = agregar42 1
|
||||
printfn "42+1 = %i" b
|
||||
|
||||
// composición para combinar funciones
|
||||
let agregar1 = agregar 1
|
||||
let agregar2 = agregar 2
|
||||
let agregar3 = agregar1 >> agregar2
|
||||
let c = agregar3 7
|
||||
printfn "3+7 = %i" c
|
||||
|
||||
// funciones de primer nivel
|
||||
[1..10] |> List.map agregar3 |> printfn "la nueva lista es %A"
|
||||
|
||||
// listas de funciones y más
|
||||
let agregar6 = [agregar1; agregar2; agregar3] |> List.reduce (>>)
|
||||
let d = agregar6 7
|
||||
printfn "1+2+3+7 = %i" d
|
||||
|
||||
// ================================================
|
||||
// Lista de colecciones
|
||||
// ================================================
|
||||
|
||||
// Il y a trois types de collection ordonnée :
|
||||
// * Les listes sont les collections immutables les plus basiques
|
||||
// * Les tableaux sont mutables et plus efficients
|
||||
// * Les séquences sont lazy et infinies (e.g. un enumerator)
|
||||
//
|
||||
// Des autres collections incluent des maps immutables et des sets
|
||||
// plus toutes les collections de .NET
|
||||
|
||||
module EjemplosDeLista =
|
||||
|
||||
// las listas utilizan corchetes
|
||||
let lista1 = ["a";"b"]
|
||||
let lista2 = "c" :: lista1 // :: para una adición al principio
|
||||
let lista3 = lista1 @ lista2 // @ para la concatenación
|
||||
|
||||
// Lista de comprensión (alias generadores)
|
||||
let cuadrados = [for i in 1..10 do yield i*i]
|
||||
|
||||
// Generador de números primos
|
||||
let rec tamiz = function
|
||||
| (p::xs) -> p :: tamiz [ for x in xs do if x % p > 0 then yield x ]
|
||||
| [] -> []
|
||||
let primos = tamiz [2..50]
|
||||
printfn "%A" primos
|
||||
|
||||
// coincidencia de patrones para listas
|
||||
let listaDeCoincidencias unaLista =
|
||||
match unaLista with
|
||||
| [] -> printfn "la lista esta vacia"
|
||||
| [primero] -> printfn "la lista tiene un elemento %A " primero
|
||||
| [primero; segundo] -> printfn "la lista es %A y %A" primero segundo
|
||||
| _ -> printfn "la lista tiene mas de dos elementos"
|
||||
|
||||
listaDeCoincidencias [1;2;3;4]
|
||||
listaDeCoincidencias [1;2]
|
||||
listaDeCoincidencias [1]
|
||||
listaDeCoincidencias []
|
||||
|
||||
// Récursion en utilisant les listes
|
||||
let rec suma unaLista =
|
||||
match unaLista with
|
||||
| [] -> 0
|
||||
| x::xs -> x + suma xs
|
||||
suma [1..10]
|
||||
|
||||
// -----------------------------------------
|
||||
// Funciones de la biblioteca estándar
|
||||
// -----------------------------------------
|
||||
|
||||
// mapeo
|
||||
let agregar3 x = x + 3
|
||||
[1..10] |> List.map agregar3
|
||||
|
||||
// filtrado
|
||||
let par x = x % 2 = 0
|
||||
[1..10] |> List.filter par
|
||||
|
||||
// mucho más - consulte la documentación
|
||||
|
||||
module EjemploDeArreglo =
|
||||
|
||||
// los arreglos usan corchetes con barras.
|
||||
let arreglo1 = [| "a";"b" |]
|
||||
let primero = arreglo1.[0] // se accede al índice usando un punto
|
||||
|
||||
// la coincidencia de patrones de los arreglos es la misma que la de las listas
|
||||
let coincidenciaDeArreglos una Lista =
|
||||
match unaLista with
|
||||
| [| |] -> printfn "la matriz esta vacia"
|
||||
| [| primero |] -> printfn "el arreglo tiene un elemento %A " primero
|
||||
| [| primero; second |] -> printfn "el arreglo es %A y %A" primero segundo
|
||||
| _ -> printfn "el arreglo tiene mas de dos elementos"
|
||||
|
||||
coincidenciaDeArreglos [| 1;2;3;4 |]
|
||||
|
||||
// La biblioteca estándar funciona como listas
|
||||
[| 1..10 |]
|
||||
|> Array.map (fun i -> i+3)
|
||||
|> Array.filter (fun i -> i%2 = 0)
|
||||
|> Array.iter (printfn "el valor es %i. ")
|
||||
|
||||
module EjemploDeSecuencia =
|
||||
|
||||
// Las secuencias usan llaves
|
||||
let secuencia1 = seq { yield "a"; yield "b" }
|
||||
|
||||
// Las secuencias pueden usar yield y
|
||||
// puede contener subsecuencias
|
||||
let extranio = seq {
|
||||
// "yield" agrega un elemento
|
||||
yield 1; yield 2;
|
||||
|
||||
// "yield!" agrega una subsecuencia completa
|
||||
yield! [5..10]
|
||||
yield! seq {
|
||||
for i in 1..10 do
|
||||
if i%2 = 0 then yield i }}
|
||||
// prueba
|
||||
extranio |> Seq.toList
|
||||
|
||||
// Las secuencias se pueden crear usando "unfold"
|
||||
// Esta es la secuencia de fibonacci
|
||||
let fib = Seq.unfold (fun (fst,snd) ->
|
||||
Some(fst + snd, (snd, fst + snd))) (0,1)
|
||||
|
||||
// prueba
|
||||
let fib10 = fib |> Seq.take 10 |> Seq.toList
|
||||
printf "Los primeros 10 fib son %A" fib10
|
||||
|
||||
// ================================================
|
||||
// Tipos de datos
|
||||
// ================================================
|
||||
|
||||
module EejemploDeTipoDeDatos =
|
||||
|
||||
// Todos los datos son inmutables por defecto
|
||||
|
||||
// las tuplas son tipos anónimos simples y rápidos
|
||||
// - Usamos una coma para crear una tupla
|
||||
let dosTuplas = 1,2
|
||||
let tresTuplas = "a",2,true
|
||||
|
||||
// Combinación de patrones para desempaquetar
|
||||
let x,y = dosTuplas // asignado x=1 y=2
|
||||
|
||||
// ------------------------------------
|
||||
// Los tipos de registro tienen campos con nombre
|
||||
// ------------------------------------
|
||||
|
||||
// Usamos "type" con llaves para definir un tipo de registro
|
||||
type Persona = {Nombre:string; Apellido:string}
|
||||
|
||||
// Usamos "let" con llaves para crear un registro
|
||||
let persona1 = {Nombre="John"; Apellido="Doe"}
|
||||
|
||||
// Combinación de patrones para desempaquetar
|
||||
let {Nombre=nombre} = persona1 // asignado nombre="john"
|
||||
|
||||
// ------------------------------------
|
||||
// Los tipos de unión (o variantes) tienen un conjunto de elección
|
||||
// Solo un caso puede ser válido a la vez.
|
||||
// ------------------------------------
|
||||
|
||||
// Usamos "type" con barra/pipe para definir una unión estándar
|
||||
type Temp =
|
||||
| GradosC of float
|
||||
| GradosF of float
|
||||
|
||||
// Una de estas opciones se usa para crear una
|
||||
let temp1 = GradosF 98.6
|
||||
let temp2 = GradosC 37.0
|
||||
|
||||
// Coincidencia de patrón en todos los casos para desempaquetar (?)
|
||||
let imprimirTemp = function
|
||||
| GradosC t -> printfn "%f gradC" t
|
||||
| GradosF t -> printfn "%f gradF" t
|
||||
|
||||
imprimirTemp temp1
|
||||
imprimirTemp temp2
|
||||
|
||||
// ------------------------------------
|
||||
// Tipos recursivos
|
||||
// ------------------------------------
|
||||
|
||||
// Los tipos se pueden combinar recursivamente de formas complejas
|
||||
// sin tener que crear subclases
|
||||
type Empleado =
|
||||
| Trabajador of Persona
|
||||
| Gerente of Empleado lista
|
||||
|
||||
let jdoe = {Nombre="John";Apellido="Doe"}
|
||||
let trabajador = Trabajador jdoe
|
||||
|
||||
// ------------------------------------
|
||||
// Modelado con tipados (?)
|
||||
// ------------------------------------
|
||||
|
||||
// Los tipos de unión son excelentes para modelar el estado sin usar banderas (?)
|
||||
type DireccionDeCorreo =
|
||||
| DireccionDeCorreoValido of string
|
||||
| DireccionDeCorreoInvalido of string
|
||||
|
||||
let intentarEnviarCorreo correoElectronico =
|
||||
match correoElectronico with // uso de patrones de coincidencia
|
||||
| DireccionDeCorreoValido direccion -> () // enviar
|
||||
| DireccionDeCorreoInvalido direccion -> () // no enviar
|
||||
|
||||
// Combinar juntos, los tipos de unión y tipos de registro
|
||||
// ofrece una base excelente para el diseño impulsado por el dominio.
|
||||
// Puedes crear cientos de pequeños tipos que reflejarán fielmente
|
||||
// el dominio.
|
||||
|
||||
type ArticuloDelCarrito = { CodigoDelProducto: string; Cantidad: int }
|
||||
type Pago = Pago of float
|
||||
type DatosActivosDelCarrito = { ArticulosSinPagar: ArticuloDelCarrito lista }
|
||||
type DatosPagadosDelCarrito = { ArticulosPagados: ArticuloDelCarrito lista; Pago: Pago}
|
||||
|
||||
type CarritoDeCompras =
|
||||
| CarritoVacio // sin datos
|
||||
| CarritoActivo of DatosActivosDelCarrito
|
||||
| CarritoPagado of DatosPagadosDelCarrito
|
||||
|
||||
// ------------------------------------
|
||||
// Comportamiento nativo de los tipos
|
||||
// ------------------------------------
|
||||
|
||||
// Los tipos nativos tienen el comportamiento más útil "listo para usar", sin ningún código para agregar.
|
||||
// * Inmutabilidad
|
||||
// * Bonita depuración de impresión
|
||||
// * Igualdad y comparación
|
||||
// * Serialización
|
||||
|
||||
// La impresión bonita se usa con %A
|
||||
printfn "dosTuplas=%A,\nPersona=%A,\nTemp=%A,\nEmpleado=%A"
|
||||
dosTuplas persona1 temp1 trabajador
|
||||
|
||||
// La igualdad y la comparación son innatas
|
||||
// Aquí hay un ejemplo con tarjetas.
|
||||
type JuegoDeCartas = Trebol | Diamante | Espada | Corazon
|
||||
type Rango = Dos | Tres | Cuatro | Cinco | Seis | Siete | Ocho
|
||||
| Nueve | Diez | Jack | Reina | Rey | As
|
||||
|
||||
let mano = [ Trebol,As; Corazon,Tres; Corazon,As;
|
||||
Espada,Jack; Diamante,Dos; Diamante,As ]
|
||||
|
||||
// orden
|
||||
List.sort mano |> printfn "la mano ordenada es (de menos a mayor) %A"
|
||||
List.max mano |> printfn "la carta más alta es%A"
|
||||
List.min mano |> printfn "la carta más baja es %A"
|
||||
|
||||
// ================================================
|
||||
// Patrones activos
|
||||
// ================================================
|
||||
|
||||
module EjemplosDePatronesActivos =
|
||||
|
||||
// F# tiene un tipo particular de coincidencia de patrón llamado "patrones activos"
|
||||
// donde el patrón puede ser analizado o detectado dinámicamente.
|
||||
|
||||
// "clips de banana" es la sintaxis de los patrones activos
|
||||
|
||||
// por ejemplo, definimos un patrón "activo" para que coincida con los tipos de "caracteres" ...
|
||||
let (|Digito|Latra|EspacioEnBlanco|Otros|) ch =
|
||||
if System.Char.IsDigit(ch) then Digito
|
||||
else if System.Char.IsLetter(ch) then Letra
|
||||
else if System.Char.IsWhiteSpace(ch) then EspacioEnBlanco
|
||||
else Otros
|
||||
|
||||
// ... y luego lo usamos para hacer que la lógica de análisis sea más clara
|
||||
let ImprimirCaracter ch =
|
||||
match ch with
|
||||
| Digito -> printfn "%c es un Digito" ch
|
||||
| Letra -> printfn "%c es una Letra" ch
|
||||
| Whitespace -> printfn "%c es un Espacio en blanco" ch
|
||||
| _ -> printfn "%c es algo mas" ch
|
||||
|
||||
// ver una lista
|
||||
['a';'b';'1';' ';'-';'c'] |> List.iter ImprimirCaracter
|
||||
|
||||
// -----------------------------------------
|
||||
// FizzBuzz usando patrones activos
|
||||
// -----------------------------------------
|
||||
|
||||
// Puede crear un patrón de coincidencia parcial también
|
||||
// Solo usamos un guión bajo en la definición y devolvemos Some si coincide.
|
||||
let (|MultDe3|_|) i = if i % 3 = 0 then Some MultDe3 else None
|
||||
let (|MultDe5|_|) i = if i % 5 = 0 then Some MultDe5 else None
|
||||
|
||||
// la función principal
|
||||
let fizzBuzz i =
|
||||
match i with
|
||||
| MultDe3 & MultDe5 -> printf "FizzBuzz, "
|
||||
| MultDe3 -> printf "Fizz, "
|
||||
| MultDe5 -> printf "Buzz, "
|
||||
| _ -> printf "%i, " i
|
||||
|
||||
// prueba
|
||||
[1..20] |> List.iter fizzBuzz
|
||||
|
||||
// ================================================
|
||||
// concisión
|
||||
// ================================================
|
||||
|
||||
module EjemploDeAlgoritmo =
|
||||
|
||||
// F# tiene una alta relación señal / ruido, lo que permite leer el código
|
||||
// casi como un algoritmo real
|
||||
|
||||
// ------ Ejemplo: definir una función sumaDeCuadrados ------
|
||||
let sumaDeCuadrados n =
|
||||
[1..n] // 1) Tome todos los números del 1 al n
|
||||
|> List.map cuadrado // 2) Elevar cada uno de ellos al cuadrado
|
||||
|> List.sum // 3) Realiza su suma
|
||||
|
||||
// prueba
|
||||
sumaDeCuadrados 100 |> printfn "Suma de cuadrados = %A"
|
||||
|
||||
// ------ Ejemplo: definir una función de ordenación ------
|
||||
let rec ordenar lista =
|
||||
match lista with
|
||||
// Si la lista está vacía
|
||||
| [] ->
|
||||
[] // devolvemos una lista vacía
|
||||
// si la lista no está vacía
|
||||
| primerElemento::otrosElementos -> // tomamos el primer elemento
|
||||
let elementosMasPequenios = // extraemos los elementos más pequeños
|
||||
otrosElementos // tomamos el resto
|
||||
|> List.filter (fun e -> e < primerElemento)
|
||||
|> ordenar // y los ordenamos
|
||||
let elementosMasGrandes = // extraemos el mas grande
|
||||
otrosElementos // de los que permanecen
|
||||
|> List.filter (fun e -> e >= primerElemento)
|
||||
|> ordenar // y los ordenamos
|
||||
// Combinamos las 3 piezas en una nueva lista que devolvemos
|
||||
List.concat [elementosMasPequenios; [primerElemento]; elementosMasGrandes]
|
||||
|
||||
// prueba
|
||||
ordenar [1;5;23;18;9;1;3] |> printfn "Ordenado = %A"
|
||||
|
||||
// ================================================
|
||||
// Código asíncrono
|
||||
// ================================================
|
||||
|
||||
module AsyncExample =
|
||||
|
||||
// F# incluye características para ayudar con el código asíncrono
|
||||
// sin conocer la "pirámide del destino"
|
||||
//
|
||||
// El siguiente ejemplo descarga una secuencia de página web en paralelo.
|
||||
|
||||
open System.Net
|
||||
open System
|
||||
open System.IO
|
||||
open Microsoft.FSharp.Control.CommonExtensions
|
||||
|
||||
// Recuperar el contenido de una URL de forma asincrónica
|
||||
let extraerUrlAsync url =
|
||||
async { // La palabra clave "async" y llaves
|
||||
// crear un objeto "asincrónico"
|
||||
let solicitud = WebRequest.Create(Uri(url))
|
||||
use! respuesta = solicitud.AsyncGetResponse()
|
||||
// use! es una tarea asincrónica
|
||||
use flujoDeDatos = resp.GetResponseStream()
|
||||
// "use" dispara automáticamente la funcion close()
|
||||
// en los recursos al final de las llaves
|
||||
use lector = new IO.StreamReader(flujoDeDatos)
|
||||
let html = lector.ReadToEnd()
|
||||
printfn "terminó la descarga %s" url
|
||||
}
|
||||
|
||||
// una lista de sitios para informar
|
||||
let sitios = ["http://www.bing.com";
|
||||
"http://www.google.com";
|
||||
"http://www.microsoft.com";
|
||||
"http://www.amazon.com";
|
||||
"http://www.yahoo.com"]
|
||||
|
||||
// ¡Aqui vamos!
|
||||
sitios
|
||||
|> List.map extraerUrlAsync // crear una lista de tareas asíncrona
|
||||
|> Async.Parallel // decirle a las tareas que se desarrollan en paralelo
|
||||
|> Async.RunSynchronously // ¡Empieza!
|
||||
|
||||
// ================================================
|
||||
// Compatibilidad .NET
|
||||
// ================================================
|
||||
|
||||
module EjemploCompatibilidadNet =
|
||||
|
||||
// F# puede hacer casi cualquier cosa que C# pueda hacer, y se ajusta
|
||||
// perfectamente con bibliotecas .NET o Mono.
|
||||
|
||||
// ------- Trabaja con las funciones de las bibliotecas existentes -------
|
||||
|
||||
let (i1success,i1) = System.Int32.TryParse("123");
|
||||
if i1success then printfn "convertido como %i" i1 else printfn "conversion fallida"
|
||||
|
||||
// ------- Implementar interfaces sobre la marcha! -------
|
||||
|
||||
// Crea un nuevo objeto que implemente IDisposable
|
||||
let crearRecurso name =
|
||||
{ new System.IDisposable
|
||||
with member this.Dispose() = printfn "%s creado" name }
|
||||
|
||||
let utilizarYDisponerDeRecursos =
|
||||
use r1 = crearRecurso "primer recurso"
|
||||
printfn "usando primer recurso"
|
||||
for i in [1..3] do
|
||||
let nombreDelRecurso = sprintf "\tinner resource %d" i
|
||||
use temp = crearRecurso nombreDelRecurso
|
||||
printfn "\thacer algo con %s" nombreDelRecurso
|
||||
use r2 = crearRecurso "segundo recurso"
|
||||
printfn "usando segundo recurso"
|
||||
printfn "hecho."
|
||||
|
||||
// ------- Código orientado a objetos -------
|
||||
|
||||
// F# es también un verdadero lenguaje OO.
|
||||
// Admite clases, herencia, métodos virtuales, etc.
|
||||
|
||||
// interfaz de tipo genérico
|
||||
type IEnumerator<'a> =
|
||||
abstract member Actual : 'a
|
||||
abstract MoverSiguiente : unit -> bool
|
||||
|
||||
// Clase base abstracta con métodos virtuales
|
||||
[<AbstractClass>]
|
||||
type Figura() =
|
||||
// propiedades de solo lectura
|
||||
abstract member Ancho : int with get
|
||||
abstract member Alto : int with get
|
||||
// método no virtual
|
||||
member this.AreaDelimitadora = this.Alto * this.Ancho
|
||||
// método virtual con implementación de la clase base
|
||||
abstract member Imprimir : unit -> unit
|
||||
default this.Imprimir () = printfn "Soy una Figura"
|
||||
|
||||
// clase concreta que hereda de su clase base y sobrecarga
|
||||
type Rectangulo(x:int, y:int) =
|
||||
inherit Figura()
|
||||
override this.Ancho = x
|
||||
override this.Alto = y
|
||||
override this.Imprimir () = printfn "Soy un Rectangulo"
|
||||
|
||||
// prueba
|
||||
let r = Rectangulo(2,3)
|
||||
printfn "La anchura es %i" r.Ancho
|
||||
printfn "El area es %i" r.AreaDelimitadora
|
||||
r.Imprimir()
|
||||
|
||||
// ------- extensión de método -------
|
||||
|
||||
// Al igual que en C#, F# puede extender las clases existentes con extensiones de método.
|
||||
type System.String with
|
||||
member this.EmpiezaConA = this.EmpiezaCon "A"
|
||||
|
||||
// prueba
|
||||
let s = "Alice"
|
||||
printfn "'%s' empieza con una 'A' = %A" s s.EmpiezaConA
|
||||
|
||||
// ------- eventos -------
|
||||
|
||||
type MiBoton() =
|
||||
let eventoClick = new Event<_>()
|
||||
|
||||
[<CLIEvent>]
|
||||
member this.AlHacerClick = eventoClick.Publish
|
||||
|
||||
member this.PruebaEvento(arg) =
|
||||
eventoClick.Trigger(this, arg)
|
||||
|
||||
// prueba
|
||||
let miBoton = new MiBoton()
|
||||
miBoton.AlHacerClick.Add(fun (sender, arg) ->
|
||||
printfn "Haga clic en el evento con arg=%O" arg)
|
||||
|
||||
miBoton.PruebaEvento("Hola Mundo!")
|
||||
```
|
||||
|
||||
## Más información
|
||||
|
||||
Para más demostraciones de F#, visite el sitio [Try F#](http://www.tryfsharp.org/Learn), o sigue la serie [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/).
|
||||
|
||||
Aprenda más sobre F# en [fsharp.org](http://fsharp.org/).
|
@ -18,7 +18,7 @@ SmallBASIC fue desarrollado originalmente por Nicholas Christopoulos a finales d
|
||||
Versiones de SmallBASIC se han hecho para una serie dispositivos de mano antiguos, incluyendo Franklin eBookman y el Nokia 770. También se han publicado varias versiones de escritorio basadas en una variedad de kits de herramientas GUI, algunas de las cuales han desaparecido. Las plataformas actualmente soportadas son Linux y Windows basadas en SDL2 y Android basadas en NDK. También está disponible una versión de línea de comandos de escritorio, aunque no suele publicarse en formato binario.
|
||||
Alrededor de 2008 una gran corporación lanzó un entorno de programación BASIC con un nombre de similar. SmallBASIC no está relacionado con este otro proyecto.
|
||||
|
||||
```SmallBASIC
|
||||
```
|
||||
REM Esto es un comentario
|
||||
' y esto tambien es un comentario
|
||||
|
||||
|
@ -14,7 +14,7 @@ fácilmente a HTML (y, actualmente, otros formatos también).
|
||||
¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
|
||||
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<!-- Markdown está basado en HTML, así que cualquier archivo HTML es Markdown
|
||||
válido, eso significa que podemos usar elementos HTML en Markdown como, por
|
||||
ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún
|
||||
|
@ -13,7 +13,7 @@ Objective C es el lenguaje de programación principal utilizado por Apple para l
|
||||
Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk".
|
||||
|
||||
|
||||
```objective_c
|
||||
```objectivec
|
||||
// Los comentarios de una sola línea inician con //
|
||||
|
||||
/*
|
||||
|
1935
es-es/perl6-es.html.markdown
Normal file
1935
es-es/perl6-es.html.markdown
Normal file
File diff suppressed because it is too large
Load Diff
@ -14,8 +14,6 @@ Es básicamente pseudocódigo ejecutable.
|
||||
|
||||
¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google]
|
||||
|
||||
Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3!
|
||||
|
||||
```python
|
||||
|
||||
# Comentarios de una línea comienzan con una almohadilla (o signo gato)
|
||||
@ -39,6 +37,8 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl
|
||||
|
||||
# Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante)
|
||||
35 / 5 # => 7.0
|
||||
# Sin embargo también tienes disponible división entera
|
||||
34 // 5 # => 6
|
||||
|
||||
# Cuando usas un float, los resultados son floats
|
||||
3 * 2.0 # => 6.0
|
||||
@ -87,11 +87,14 @@ not False # => True
|
||||
# .format puede ser usaro para darle formato a los strings, así:
|
||||
"{} pueden ser {}".format("strings", "interpolados")
|
||||
|
||||
# Puedes repetir los argumentos de formateo para ahorrar tipeos.
|
||||
# Puedes reutilizar los argumentos de formato si estos se repiten.
|
||||
"{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela"
|
||||
# Puedes usar palabras claves si no quieres contar.
|
||||
"{nombre} quiere comer {comida}".format(nombre="Bob", food="lasaña") #=> "Bob quiere comer lasaña"
|
||||
|
||||
"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña"
|
||||
# También puedes interpolar cadenas usando variables en el contexto
|
||||
nombre = 'Bob'
|
||||
comida = 'Lasaña'
|
||||
f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña"
|
||||
|
||||
# None es un objeto
|
||||
None # => None
|
||||
@ -101,12 +104,13 @@ None # => None
|
||||
"etc" is None #=> False
|
||||
None is None #=> True
|
||||
|
||||
# None, 0, y strings/listas/diccionarios vacíos(as) todos se evalúan como False.
|
||||
# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False.
|
||||
# Todos los otros valores son True
|
||||
bool(0) # => False
|
||||
bool("") # => False
|
||||
bool([]) #=> False
|
||||
bool({}) #=> False
|
||||
bool(set()) #=> False
|
||||
|
||||
|
||||
####################################################
|
||||
@ -170,7 +174,7 @@ lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan
|
||||
# Concatenar listas con 'extend'
|
||||
lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6]
|
||||
|
||||
# Chequea la existencia en una lista con 'in'
|
||||
# Verifica la existencia en una lista con 'in'
|
||||
1 in lista #=> True
|
||||
|
||||
# Examina el largo de una lista con 'len'
|
||||
@ -196,7 +200,7 @@ d, e, f = 4, 5, 6
|
||||
e, d = d, e # d ahora es 5 y e ahora es 4
|
||||
|
||||
|
||||
# Diccionarios almacenan mapeos
|
||||
# Diccionarios relacionan llaves y valores
|
||||
dicc_vacio = {}
|
||||
# Aquí está un diccionario prellenado
|
||||
dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
|
||||
@ -213,7 +217,7 @@ list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"]
|
||||
list(dicc_lleno.values()) #=> [3, 2, 1]
|
||||
# Nota - Lo mismo que con las llaves, no se garantiza el orden.
|
||||
|
||||
# Chequea la existencia de una llave en el diccionario con 'in'
|
||||
# Verifica la existencia de una llave en el diccionario con 'in'
|
||||
"uno" in dicc_lleno #=> True
|
||||
1 in dicc_lleno #=> False
|
||||
|
||||
@ -253,7 +257,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6}
|
||||
# Haz diferencia de conjuntos con -
|
||||
{1,2,3,4} - {2,3,5} #=> {1, 4}
|
||||
|
||||
# Chequea la existencia en un conjunto con 'in'
|
||||
# Verifica la existencia en un conjunto con 'in'
|
||||
2 in conjunto_lleno #=> True
|
||||
10 in conjunto_lleno #=> False
|
||||
|
||||
@ -262,7 +266,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6}
|
||||
## 3. Control de Flujo
|
||||
####################################################
|
||||
|
||||
# Let's just make a variable
|
||||
# Creemos una variable para experimentar
|
||||
some_var = 5
|
||||
|
||||
# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python!
|
||||
@ -275,18 +279,17 @@ else: # Esto también es opcional.
|
||||
print("una_variable es de hecho 10.")
|
||||
|
||||
"""
|
||||
For itera sobre listas
|
||||
For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...)
|
||||
imprime:
|
||||
perro es un mamifero
|
||||
gato es un mamifero
|
||||
raton es un mamifero
|
||||
"""
|
||||
for animal in ["perro", "gato", "raton"]:
|
||||
# Puedes usar % para interpolar strings formateados
|
||||
print("{} es un mamifero".format(animal))
|
||||
|
||||
"""
|
||||
`range(número)` retorna una lista de números
|
||||
`range(número)` retorna un generador de números
|
||||
desde cero hasta el número dado
|
||||
imprime:
|
||||
0
|
||||
@ -323,7 +326,7 @@ except IndexError as e:
|
||||
|
||||
dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
|
||||
nuestro_iterable = dicc_lleno.keys()
|
||||
print(nuestro_iterable) #=> range(1,10). Este es un objeto que implementa nuestra interfaz Iterable
|
||||
print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable
|
||||
|
||||
Podemos recorrerla.
|
||||
for i in nuestro_iterable:
|
||||
@ -420,6 +423,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
|
||||
# Podemos usar listas por comprensión para mapeos y filtros agradables
|
||||
[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]
|
||||
# también hay diccionarios
|
||||
{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4}
|
||||
# y conjuntos por comprensión
|
||||
{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'}
|
||||
|
||||
####################################################
|
||||
## 5. Classes
|
||||
|
@ -10,7 +10,7 @@ filename: learnvisualbasic-es.vb
|
||||
lang: es-es
|
||||
---
|
||||
|
||||
```vb
|
||||
```
|
||||
Module Module1
|
||||
|
||||
Sub Main()
|
||||
|
@ -9,7 +9,7 @@ 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.
|
||||
|
||||
```
|
||||
```factor
|
||||
! This is a comment
|
||||
|
||||
! Like Forth, all programming is done by manipulating the stack.
|
||||
|
@ -10,7 +10,7 @@ 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
|
||||
```md
|
||||
<!-- 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
|
||||
|
@ -910,7 +910,6 @@ v.swap(vector<Foo>());
|
||||
```
|
||||
Lecture complémentaire :
|
||||
|
||||
Une référence à jour du langage est disponible à
|
||||
<http://cppreference.com/w/cpp>
|
||||
|
||||
Des ressources supplémentaires sont disponibles à <http://cplusplus.com>
|
||||
* Une référence à jour du langage est disponible à [CPP Reference](http://cppreference.com/w/cpp).
|
||||
* Des ressources supplémentaires sont disponibles à [CPlusPlus](http://cplusplus.com).
|
||||
* Un tutoriel couvrant les bases du langage et la configuration d'un environnement de codage est disponible à l'adresse [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb).
|
||||
|
@ -305,7 +305,6 @@ end
|
||||
(1..3).each do |index|
|
||||
puts "Index: #{index}"
|
||||
end
|
||||
# Index: 0
|
||||
# Index: 1
|
||||
# Index: 2
|
||||
# Index: 3
|
||||
|
@ -8,7 +8,6 @@ translators:
|
||||
lang: fr-fr
|
||||
---
|
||||
|
||||
|
||||
# Programmation dynamique
|
||||
|
||||
## Introduction
|
||||
@ -17,9 +16,9 @@ La programmation dynamique est une technique très efficace pour résoudre une c
|
||||
|
||||
## Moyens de résoudre ces problèmes
|
||||
|
||||
1.) *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation.
|
||||
1. *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation.
|
||||
|
||||
2.) *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique.
|
||||
2. *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique.
|
||||
|
||||
## Exemple de Programmation Dynamique
|
||||
|
||||
@ -27,7 +26,7 @@ Le problème de la plus grande sous-chaîne croissante est de trouver la plus gr
|
||||
Premièrement, nous avons à trouver la valeur de la plus grande sous-chaîne (LSi) à chaque index `i`, avec le dernier élément de la sous-chaîne étant ai. Alors, la plus grande sous-chaîne sera le plus gros LSi. Pour commencer, LSi est égal à 1, car ai est le seul élément de la chaîne (le dernier). Ensuite, pour chaque `j` tel que `j<i` et `aj<ai`, nous trouvons le plus grand LSj et ajoutons le à LSi. L'algorithme fonctionne en temps *O(n2)*.
|
||||
|
||||
Pseudo-code pour trouver la longueur de la plus grande sous-chaîne croissante :
|
||||
La complexité de cet algorithme peut être réduite en utilisant une meilleure structure de données qu'un tableau. Par exemple, si nous sauvegardions le tableau d'origine, ou une variable comme plus_grande_chaîne_jusqu'à_maintenant et son index, nous pourrions sauver beaucoup de temps.
|
||||
La complexité de cet algorithme peut être réduite en utilisant une meilleure structure de données qu'un tableau. Par exemple, si nous sauvegardions le tableau d'origine, ou une variable comme `plus_grande_chaîne_jusqu'à_maintenant` et son index, nous pourrions sauver beaucoup de temps.
|
||||
|
||||
Le même concept peut être appliqué pour trouver le chemin le plus long dans un graphe acyclique orienté.
|
||||
|
||||
@ -43,12 +42,9 @@ Le même concept peut être appliqué pour trouver le chemin le plus long dans u
|
||||
|
||||
### Problèmes classiques de programmation dynamique
|
||||
|
||||
L'algorithme de Floyd Warshall(EN)) - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
|
||||
|
||||
Problème du sac à dos(EN) - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
|
||||
|
||||
|
||||
Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
|
||||
- L'algorithme de Floyd Warshall(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]()
|
||||
- Problème du sac à dos(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]()
|
||||
- Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]()
|
||||
|
||||
## Online Resources
|
||||
|
||||
|
@ -11,7 +11,7 @@ contributors:
|
||||
- ["Michael Dähnert", "https://github.com/JaXt0r"]
|
||||
- ["Rob Rose", "https://github.com/RobRoseKnows"]
|
||||
- ["Sean Nam", "https://github.com/seannam"]
|
||||
filename: JavaFr.java
|
||||
filename: java-fr.java
|
||||
translators:
|
||||
- ['Mathieu Gemard', 'https://github.com/mgemard']
|
||||
lang: fr-fr
|
||||
|
@ -13,6 +13,7 @@ jQuery est une bibliothèque JavaScript dont le but est de permettre de "faire p
|
||||
C'est pourquoi aujourd'hui, jQuery est utilisée par de nombreuses grandes entreprises et par des développeurs du monde entier.
|
||||
|
||||
Étant donné que jQuery est une bibliothèque JavaScript, vous devriez d'abord [apprendre le JavaScript](https://learnxinyminutes.com/docs/fr-fr/javascript-fr/)
|
||||
|
||||
```js
|
||||
|
||||
|
||||
@ -138,5 +139,5 @@ $('p').each(function() {
|
||||
});
|
||||
|
||||
|
||||
``
|
||||
```
|
||||
|
||||
|
106
fr-fr/lambda-calculus-fr.html.markdown
Normal file
106
fr-fr/lambda-calculus-fr.html.markdown
Normal file
@ -0,0 +1,106 @@
|
||||
---
|
||||
category: Algorithms & Data Structures
|
||||
name: Lambda Calculus
|
||||
contributors:
|
||||
- ["Max Sun", "http://github.com/maxsun"]
|
||||
translators:
|
||||
- ["Yvan Sraka", "https://github.com/yvan-sraka"]
|
||||
lang: fr-fr
|
||||
---
|
||||
|
||||
# Lambda-calcul
|
||||
|
||||
Le Lambda-calcul (λ-calcul), créé à l'origine par [Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), est le plus petit langage de programmation au monde. En dépit de ne pas avoir de nombres, de chaînes, de booléens, ou de tout type de données sans fonction, le lambda calcul peut être utilisé pour représenter n'importe quelle machine de Turing!
|
||||
|
||||
Le Lambda-calcul est composé de 3 éléments : **variables**, **fonctions** et **applications**.
|
||||
|
||||
|
||||
| Nom | Syntaxe | Exemple | Explication |
|
||||
|-------------|------------------------------------|-----------|---------------------------------------------------|
|
||||
| Variable | `<nom>` | `x` | une variable nommée "x" |
|
||||
| Fonction | `λ<paramètres>.<corps>` | `λx.x` | une fonction avec le paramètre "x" et le corps "x"|
|
||||
| Application | `<fonction><variable ou function>` | `(λx.x)a` | appel de la fonction "λx.x" avec l'argument "a" |
|
||||
|
||||
La fonction la plus fondamentale est la fonction identité: `λx.x` qui est équivalente à `f(x) = x`. Le premier "x" est l'argument de la fonction, et le second est le corps de la fonction.
|
||||
|
||||
## Variables libres et liées :
|
||||
|
||||
- Dans la fonction `λx.x`, "x" s'appelle une variable liée car elle est à la fois dans le corps de la fonction et l'un des paramètres.
|
||||
- Dans `λx.y`, "y" est appelé une variable libre car elle n'a pas été déclarée plus tôt.
|
||||
|
||||
## Évaluation :
|
||||
|
||||
L'évaluation est réalisée par [β-Réduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), qui est essentiellement une substitution lexicale.
|
||||
|
||||
Lors de l'évaluation de l'expression `(λx.x)a`, nous remplaçons toutes les occurrences de "x" dans le corps de la fonction par "a".
|
||||
|
||||
- `(λx.x)a` vaut après évaluation: `a`
|
||||
- `(λx.y)a` vaut après évaluation: `y`
|
||||
|
||||
Vous pouvez même créer des fonctions d'ordre supérieur:
|
||||
|
||||
- `(λx.(λy.x))a` vaut après évaluation: `λy.a`
|
||||
|
||||
Bien que le lambda-calcul ne prenne traditionnellement en charge que les fonctions à un seul paramètre, nous pouvons créer des fonctions multi-paramètres en utilisant une technique appelée currying.
|
||||
|
||||
- `(λx.λy.λz.xyz)` est équivalent à `f(x, y, z) = x(y(z))`
|
||||
|
||||
Parfois, `λxy.<corps>` est utilisé de manière interchangeable avec: `λx.λy.<corps>`
|
||||
|
||||
----
|
||||
|
||||
Il est important de reconnaître que le lambda-calcul traditionnel n'a pas de nombres, de caractères ou tout autre type de données sans fonction!
|
||||
|
||||
## Logique booléenne :
|
||||
|
||||
Il n'y a pas de "Vrai" ou de "Faux" dans le calcul lambda. Il n'y a même pas 1 ou 0.
|
||||
|
||||
Au lieu:
|
||||
|
||||
`T` est représenté par: `λx.λy.x`
|
||||
|
||||
`F` est représenté par: `λx.λy.y`
|
||||
|
||||
Premièrement, nous pouvons définir une fonction "if" `λbtf` qui renvoie `t` si `b` est vrai et `f` si `b` est faux
|
||||
|
||||
`IF` est équivalent à: `λb.λt.λf.b t f`
|
||||
|
||||
En utilisant `IF`, nous pouvons définir les opérateurs logiques de base booléens:
|
||||
|
||||
`a AND b` est équivalent à: `λab.IF a b F`
|
||||
|
||||
`a OR b` est équivalent à: `λab.IF a T b`
|
||||
|
||||
`a NOT b` est équivalent à: `λa.IF a F T`
|
||||
|
||||
*Note: `IF a b c` est equivalent à : `IF(a(b(c)))`*
|
||||
|
||||
## Nombres :
|
||||
|
||||
Bien qu'il n'y ait pas de nombres dans le lambda-calcul, nous pouvons encoder des nombres en utilisant les [nombres de Church](https://en.wikipedia.org/wiki/Church_encoding).
|
||||
|
||||
Pour tout nombre n: <code>n = λf.f<sup>n</sup></code> donc:
|
||||
|
||||
`0 = λf.λx.x`
|
||||
|
||||
`1 = λf.λx.f x`
|
||||
|
||||
`2 = λf.λx.f(f x)`
|
||||
|
||||
`3 = λf.λx.f(f(f x))`
|
||||
|
||||
Pour incrémenter un nombre de Church, nous utilisons la fonction successeur `S(n) = n + 1` qui est:
|
||||
|
||||
`S = λn.λf.λx.f((n f) x)`
|
||||
|
||||
En utilisant `S`, nous pouvons définir la fonction `ADD`:
|
||||
|
||||
`ADD = λab.(a S)n`
|
||||
|
||||
**Défi:** essayez de définir votre propre fonction de multiplication!
|
||||
|
||||
## Pour aller plus loin :
|
||||
|
||||
1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf)
|
||||
2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html)
|
||||
3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus)
|
@ -6,52 +6,69 @@ filename: markdown-fr.md
|
||||
lang: fr-fr
|
||||
---
|
||||
|
||||
|
||||
Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe
|
||||
facile à lire et à écrire, aisément convertible en HTML
|
||||
(et beaucoup d'autres formats aussi à présent).
|
||||
facile à lire et à écrire, aisément convertible en HTML (et dans beaucoup
|
||||
d'autres formats aussi).
|
||||
|
||||
Faites moi autant de retours que vous voulez! Sentez vous libre de "forker"
|
||||
et envoyer des pull request!
|
||||
Les implémentations du Markdown varient d'un analyseur syntaxique à un autre.
|
||||
Ce guide va essayer de clarifier quand une fonctionnalité est universelle ou
|
||||
quand elle est specifique à un certain analyseur syntaxique.
|
||||
|
||||
- [Balises HTML](#balises-html)
|
||||
- [En-têtes](#en-tetes)
|
||||
- [Styles de texte basiques](#style-de-text-basiques)
|
||||
- [Paragraphes](#paragraphes)
|
||||
- [Listes](#listes)
|
||||
- [Blocs de code](#blocs-de-code)
|
||||
- [Séparateur horizontal](#separateur-horizontal)
|
||||
- [Liens hypertextes](#liens-hypertextes)
|
||||
- [Images](#images)
|
||||
- [Divers](#divers)
|
||||
|
||||
```markdown
|
||||
<!-- Markdown est une sorte de cousin du HTML, si bien que tout document HTML
|
||||
est un document Markdown valide. Autrement dit, vous pouvez utiliser des
|
||||
balises HTML dans un fichier Markdown, comme la balise commentaire dans
|
||||
laquelle nous sommes à présent, car celle-ci ne sera pas affectée par
|
||||
le parser( analyseur syntaxique ) Markdown. -->
|
||||
## Balises HTML
|
||||
|
||||
<!-- Toutefois, si vous voulez créer un élément HTML dans un fichier Markdown,
|
||||
vous ne pourrez pas utiliser du Markdown à l'intérieur de ce dernier. -->
|
||||
Markdown est un sur-ensemble du HTML, donc tout fichier HTML est un ficher
|
||||
Markdown valide.
|
||||
|
||||
<!-- Le Markdown est implémenté de différentes manières, selon le parser.
|
||||
Ce guide va alors tenter de trier les fonctionnalités universelles de celles
|
||||
spécifiques à un parser. -->
|
||||
```md
|
||||
<!-- Ce qui veut dire que vous pouvez utiliser des balises HTML dans un fichier
|
||||
Markdown, comme la balise commentaire dans laquelle nous sommes à présent, car
|
||||
celle-ci ne sera pas affectée par l'analyseur syntaxique du Markdown.
|
||||
Toutefois, si vous voulez créer une balise HTML dans un fichier Markdown,
|
||||
vous ne pourrez pas utiliser du Markdown à l'intérieur de cette derniere. -->
|
||||
```
|
||||
|
||||
<!-- Headers ( En-têtes ) -->
|
||||
<!-- Vous pouvez facilement créer des éléments HTML <h1> à <h6> en précédant
|
||||
le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six,
|
||||
selon le niveau de titre souhaité. -->
|
||||
## En-têtes
|
||||
|
||||
Vous pouvez facilement créer des balises HTML `<h1>` à `<h6>` en précédant le
|
||||
texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, selon
|
||||
le niveau de titre souhaité.
|
||||
|
||||
```md
|
||||
# Ceci est un <h1>
|
||||
## Ceci est un <h2>
|
||||
### Ceci est un <h3>
|
||||
#### Ceci est un <h4>
|
||||
##### Ceci est un <h5>
|
||||
###### Ceci est un <h6>
|
||||
```
|
||||
|
||||
<!--
|
||||
Markdown fournit également une façon alternative de marquer les h1 et h2
|
||||
-->
|
||||
Markdown fournit également une façon alternative de marquer les h1 et h2.
|
||||
|
||||
```md
|
||||
Ceci est un h1
|
||||
=============
|
||||
|
||||
Ceci est un h2
|
||||
-------------
|
||||
```
|
||||
|
||||
<!-- Styles basiques pour du texte -->
|
||||
<!-- On peut facilement rendre un texte "gras" ou "italique" en Markdown -->
|
||||
## Styles de texte basiques
|
||||
|
||||
On peut facilement rendre un texte "gras" ou "italique" en Markdown.
|
||||
|
||||
```md
|
||||
*Ce texte est en italique.*
|
||||
_Celui-ci aussi._
|
||||
|
||||
@ -61,15 +78,21 @@ __Celui-là aussi.__
|
||||
***Ce texte a les deux styles.***
|
||||
**_Pareil ici_**
|
||||
*__Et là!__*
|
||||
```
|
||||
|
||||
<!-- Dans le "GitHub Flavored Markdown", utilisé pour interpréter le Markdown
|
||||
sur GitHub, on a également le strikethrough ( texte barré ) : -->
|
||||
Dans le "GitHub Flavored Markdown", utilisé pour interpréter le Markdown sur
|
||||
GitHub, on a également le texte barré.
|
||||
|
||||
~~Ce texte est barré avec strikethrough.~~
|
||||
```md
|
||||
~~Ce texte est barré.~~
|
||||
```
|
||||
|
||||
<!-- Les Paragraphes sont représentés par une ou plusieurs lignes de texte
|
||||
séparées par une ou plusieurs lignes vides. -->
|
||||
## Paragraphes
|
||||
|
||||
Les paragraphes sont représentés par une ou plusieurs lignes de texte séparées
|
||||
par une ou plusieurs lignes vides.
|
||||
|
||||
```md
|
||||
Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non?
|
||||
|
||||
Maintenant je suis dans le paragraphe 2.
|
||||
@ -77,21 +100,23 @@ Je suis toujours dans le paragraphe 2!
|
||||
|
||||
|
||||
Puis là, eh oui, le paragraphe 3!
|
||||
```
|
||||
|
||||
<!--
|
||||
Si jamais vous souhaitez insérer une balise HTML <br />, vous pouvez ajouter
|
||||
un ou plusieurs espaces à la fin de votre paragraphe, et en commencer
|
||||
un nouveau.
|
||||
-->
|
||||
Si jamais vous souhaitez insérer une balise HTML `<br />`, vous pouvez ajouter
|
||||
un ou plusieurs espaces à la fin de votre paragraphe, et en commencer un
|
||||
nouveau.
|
||||
|
||||
J'ai deux espaces vides à la fin (sélectionnez moi pour les voir).
|
||||
```md
|
||||
J'ai deux espaces vides à la fin (sélectionnez moi pour les voir).
|
||||
|
||||
Bigre, il y a un <br /> au dessus de moi!
|
||||
```
|
||||
|
||||
<!-- Les 'Blocs de Citations' sont générés aisément, grâce au caractère > -->
|
||||
Les blocs de citations sont générés aisément, grâce au caractère >.
|
||||
|
||||
```md
|
||||
> Ceci est une superbe citation. Vous pouvez même
|
||||
> revenir à la ligne quand ça vous chante, et placer un `>`
|
||||
> revenir à la ligne quand ça vous chante, et placer un `>`
|
||||
> devant chaque bout de ligne faisant partie
|
||||
> de la citation.
|
||||
> La taille ne compte pas^^ tant que chaque ligne commence par un `>`.
|
||||
@ -99,191 +124,248 @@ Bigre, il y a un <br /> au dessus de moi!
|
||||
> Vous pouvez aussi utiliser plus d'un niveau
|
||||
>> d'imbrication!
|
||||
> Classe et facile, pas vrai?
|
||||
```
|
||||
|
||||
<!-- les Listes -->
|
||||
<!-- les Listes non ordonnées sont marquées par des asterisques,
|
||||
signes plus ou signes moins. -->
|
||||
## Listes
|
||||
|
||||
Les listes non ordonnées sont marquées par des asterisques, signes plus ou
|
||||
signes moins.
|
||||
|
||||
```md
|
||||
* Item
|
||||
* Item
|
||||
* Un autre item
|
||||
```
|
||||
|
||||
ou
|
||||
|
||||
```md
|
||||
+ Item
|
||||
+ Item
|
||||
+ Encore un item
|
||||
```
|
||||
|
||||
ou
|
||||
|
||||
```md
|
||||
- Item
|
||||
- Item
|
||||
- Un dernier item
|
||||
```
|
||||
|
||||
<!-- les Listes Ordonnées sont générées via un nombre suivi d'un point -->
|
||||
Les listes ordonnées sont générées via un nombre suivi d'un point.
|
||||
|
||||
```md
|
||||
1. Item un
|
||||
2. Item deux
|
||||
3. Item trois
|
||||
```
|
||||
|
||||
<!-- Vous pouvez même vous passer de tout numéroter, et Markdown générera
|
||||
les bons chiffres. Ceci dit, cette variante perd en clarté.-->
|
||||
Vous pouvez même vous passer de tout numéroter, et Markdown générera les bons
|
||||
chiffres. Ceci dit, cette variante perd en clarté.
|
||||
|
||||
```md
|
||||
1. Item un
|
||||
1. Item deux
|
||||
1. Item trois
|
||||
<!-- ( cette liste sera interprétée de la même façon que celle au dessus ) -->
|
||||
```
|
||||
|
||||
<!-- Vous pouvez également utiliser des sous-listes -->
|
||||
(Cette liste sera interprétée de la même façon que celle au dessus)
|
||||
|
||||
Vous pouvez également utiliser des sous-listes.
|
||||
|
||||
```md
|
||||
1. Item un
|
||||
2. Item deux
|
||||
3. Item trois
|
||||
* Sub-item
|
||||
* Sub-item
|
||||
4. Item quatre
|
||||
```
|
||||
|
||||
<!-- Il y a même des "listes de Taches". Elles génèrent des champs HTML
|
||||
de type checkbox. -->
|
||||
|
||||
Les [ ] ci dessous, n'ayant pas de [ x ],
|
||||
deviendront des cases à cocher HTML non-cochées.
|
||||
Il y a même des listes de taches. Elles génèrent des champs HTML de type case à
|
||||
cocher.
|
||||
|
||||
```md
|
||||
Les [ ] ci-dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML
|
||||
non-cochées.
|
||||
- [ ] Première tache à réaliser.
|
||||
- [ ] Une autre chose à faire.
|
||||
La case suivante sera une case à cocher HTML cochée.
|
||||
- [x] Ça ... c'est fait!
|
||||
```
|
||||
|
||||
<!-- les Blocs de Code -->
|
||||
<!-- Pour marquer du texte comme étant du code, il suffit de commencer
|
||||
chaque ligne en tapant 4 espaces (ou un Tab) -->
|
||||
## Blocs de code
|
||||
|
||||
Pour marquer du texte comme étant du code (qui utilise la balise `<code>`), il
|
||||
suffit d'indenter chaque ligne avec 4 espaces ou une tabulation.
|
||||
|
||||
```md
|
||||
echo "Ça, c'est du Code!";
|
||||
var Ça = "aussi !";
|
||||
```
|
||||
|
||||
<!-- L'indentation par tab ou série de quatre espaces
|
||||
fonctionne aussi à l'intérieur du bloc de code -->
|
||||
L'indentation par tabulation (ou série de quatre espaces) fonctionne aussi à
|
||||
l'intérieur du bloc de code.
|
||||
|
||||
```md
|
||||
my_array.each do |item|
|
||||
puts item
|
||||
end
|
||||
```
|
||||
|
||||
<!-- Des bouts de code en mode 'inline' s'ajoutent en les entourant de ` -->
|
||||
Des bouts de code en mode en ligne s'ajoutent en utilisant le caractères
|
||||
`` ` ``.
|
||||
|
||||
```md
|
||||
La fonction `run()` ne vous oblige pas à aller courir!
|
||||
```
|
||||
|
||||
<!-- Via GitHub Flavored Markdown, vous pouvez utiliser
|
||||
des syntaxes spécifiques -->
|
||||
En "GitHub Flavored Markdown", vous pouvez utiliser des syntaxes spécifiques
|
||||
selon le language.
|
||||
|
||||
\`\`\`ruby
|
||||
<!-- mais enlevez les backslashes quand vous faites ça,
|
||||
gardez juste ```ruby ( ou nom de la syntaxe correspondant à votre code )-->
|
||||
<pre>
|
||||
<code class="highlight">```ruby
|
||||
def foobar
|
||||
puts "Hello world!"
|
||||
puts "Hello world!"
|
||||
end
|
||||
\`\`\` <!-- pareil, pas de backslashes, juste ``` en guise de fin -->
|
||||
```</code>
|
||||
</pre>
|
||||
|
||||
<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub
|
||||
va utiliser une coloration syntaxique pour le langage indiqué après les ``` -->
|
||||
Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub va
|
||||
utiliser une coloration syntaxique pour le langage indiqué après les \`\`\`.
|
||||
|
||||
<!-- Ligne Horizontale (<hr />) -->
|
||||
<!-- Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets,
|
||||
avec ou sans espaces entre chaque un. -->
|
||||
## Séparateur horizontal
|
||||
|
||||
La balise `<hr/>` peut être aisement ajoutée en utilisant trois ou plus
|
||||
astérisques ou tirets, avec ou sans espaces entre chacun.
|
||||
|
||||
```md
|
||||
***
|
||||
---
|
||||
- - -
|
||||
****************
|
||||
```
|
||||
|
||||
<!-- Liens -->
|
||||
<!-- Une des fonctionnalités sympathiques du Markdown est la facilité
|
||||
d'ajouter des liens. Le texte du lien entre [ ], l'url entre ( ),
|
||||
et voilà l'travail.
|
||||
-->
|
||||
## Liens hypertextes
|
||||
|
||||
Une des fonctionnalités sympathiques du Markdown est la facilité d'ajouter des
|
||||
liens hypertextes. Le texte du lien entre crochet `` [] ``, l'url entre
|
||||
parenthèses `` () ``, et voilà le travail.
|
||||
|
||||
```md
|
||||
[Clic moi!](http://test.com/)
|
||||
```
|
||||
|
||||
<!--
|
||||
Pour ajouter un attribut Title, collez le entre guillemets, avec le lien.
|
||||
-->
|
||||
Pour ajouter un attribut titre, ajoutez le entre les parenthèses entre
|
||||
guillemets apres le lien.
|
||||
|
||||
```md
|
||||
[Clic moi!](http://test.com/ "Lien vers Test.com")
|
||||
```
|
||||
|
||||
<!-- les Liens Relatifs marchent aussi -->
|
||||
Markdown supporte aussi les liens relatifs.
|
||||
|
||||
```md
|
||||
[En avant la musique](/music/).
|
||||
```
|
||||
|
||||
<!-- Les liens façon "références" sont eux aussi disponibles en Markdown -->
|
||||
Les liens de références sont eux aussi disponibles en Markdown.
|
||||
|
||||
```md
|
||||
[Cliquez ici][link1] pour plus d'information!
|
||||
[Regardez aussi par ici][foobar] si vous voulez.
|
||||
|
||||
[link1]: http://test.com/ "Cool!"
|
||||
[foobar]: http://foobar.biz/ "Alright!"
|
||||
[foobar]: http://foobar.biz/ "Génial!"
|
||||
```
|
||||
|
||||
<!-- Le titre peut aussi être entouré de guillemets simples,
|
||||
entre parenthèses ou absent. Les références peuvent être placées
|
||||
un peu où vous voulez dans le document, et les identifiants
|
||||
(link1, foobar, ...) quoi que ce soit tant qu'ils sont uniques -->
|
||||
Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou
|
||||
absent. Les références peuvent être placées où vous voulez dans le document et
|
||||
les identifiants peuvent être n'importe quoi tant qu'ils sont uniques.
|
||||
|
||||
<!-- Il y a également le "nommage implicite" qui transforme le texte du lien
|
||||
en identifiant -->
|
||||
Il y a également le nommage implicite qui transforme le texte du lien en
|
||||
identifiant.
|
||||
|
||||
```md
|
||||
[Ceci][] est un lien.
|
||||
|
||||
[ceci]: http://ceciestunlien.com/
|
||||
```
|
||||
|
||||
<!-- mais ce n'est pas beaucoup utilisé. -->
|
||||
Mais ce n'est pas beaucoup utilisé.
|
||||
|
||||
<!-- Images -->
|
||||
<!-- Pour les images, la syntaxe est identique aux liens, sauf que précédée
|
||||
d'un point d'exclamation! -->
|
||||
## Images
|
||||
|
||||
Pour les images, la syntaxe est identique à celle des liens, sauf que précédée
|
||||
d'un point d'exclamation!
|
||||
|
||||
```md
|
||||
![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel")
|
||||
```
|
||||
|
||||
<!-- Là aussi, on peut utiliser le mode "références" -->
|
||||
Là aussi, on peut utiliser les références.
|
||||
|
||||
```md
|
||||
![Ceci est l'attribut ALT de l'image][monimage]
|
||||
|
||||
[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici."
|
||||
```
|
||||
|
||||
<!-- Divers -->
|
||||
<!-- Liens Automatiques -->
|
||||
## Divers
|
||||
|
||||
### Liens hypertextes automatiques
|
||||
|
||||
```md
|
||||
<http://testwebsite.com/> est équivalent à :
|
||||
[http://testwebsite.com/](http://testwebsite.com/)
|
||||
```
|
||||
|
||||
<!-- Liens Automatiques pour emails -->
|
||||
### Liens hypertextes automatiques pour emails
|
||||
|
||||
```md
|
||||
<foo@bar.com>
|
||||
```
|
||||
|
||||
### Caracteres d'echappement
|
||||
|
||||
<!-- Escaping -->
|
||||
Il suffit de précéder les caractères spécifiques à ignorer par des backslash \
|
||||
|
||||
Pour taper *ce texte* entouré d'astérisques mais pas en italique :
|
||||
```md
|
||||
Pour taper *ce texte* entouré d'astérisques mais pas en italique :
|
||||
Tapez \*ce texte\*.
|
||||
```
|
||||
|
||||
<!-- Tableaux -->
|
||||
<!-- les Tableaux ne sont disponibles que dans le GitHub Flavored Markdown
|
||||
et c'est ce n'est pas super agréable d'utilisation.
|
||||
Mais si vous en avez besoin :
|
||||
-->
|
||||
### Touches de clavier
|
||||
|
||||
Avec le "Github Flavored Markdown", vous pouvez utiliser la balise `<kdb>`
|
||||
pour représenter une touche du clavier.
|
||||
|
||||
```md
|
||||
Ton ordinateur a planté? Essayer de taper :
|
||||
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||
```
|
||||
|
||||
### Tableaux
|
||||
|
||||
Les tableaux ne sont disponibles que dans le "GitHub Flavored Markdown" et
|
||||
ne sont pas tres agréable d'utilisation. Mais si vous en avez besoin :
|
||||
|
||||
```md
|
||||
| Col1 | Col2 | Col3 |
|
||||
| :----------- | :------: | ------------: |
|
||||
| Alignement Gauche | Centé | Alignement Droite |
|
||||
| bla | bla | bla |
|
||||
```
|
||||
|
||||
<!-- ou bien, pour un résultat équivalent : -->
|
||||
ou bien, pour un résultat équivalent :
|
||||
|
||||
```md
|
||||
Col 1 | Col2 | Col3
|
||||
:-- | :-: | --:
|
||||
Ough que c'est moche | svp | arrêtez
|
||||
|
||||
<!-- Fin! -->
|
||||
|
||||
```
|
||||
|
||||
Pour plus d'information :
|
||||
consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe,
|
||||
et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard.
|
||||
Pour plus d'information, consultez le post officiel de Jhon Gruber à propos de
|
||||
la syntaxe [ici](http://daringfireball.net/projects/markdown/syntax) et la
|
||||
superbe fiche pense-bête de Adam Pritchard [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
||||
|
85
fr-fr/pyqt-fr.html.markdown
Normal file
85
fr-fr/pyqt-fr.html.markdown
Normal file
@ -0,0 +1,85 @@
|
||||
---
|
||||
category: tool
|
||||
tool: PyQT
|
||||
filename: learnpyqt-fr.py
|
||||
contributors:
|
||||
- ["Nathan Hughes", "https://github.com/sirsharpest"]
|
||||
translators:
|
||||
- ["DevHugo", "http://twitter.com/devhugo"]
|
||||
lang: fr-fr
|
||||
---
|
||||
|
||||
**Qt** est un framework très connu pour le développement de logiciel cross-platform qui peuvent être lancé sur différents systèmes avec de petit ou aucun changement dans le code, tout en ayant la puissance et la vitesse des applications natives. Bien que **Qt** ait été écrit à l'origine en *C++*.
|
||||
|
||||
|
||||
Ceci est une adaptation de l'intro C++ à QT par [Aleksey Kholovchuk](https://github.com/vortexxx192
|
||||
), certains exemples du code doivent avoir la même fonctionnalité,
|
||||
cette version ayant juste été faite en utilisant pyqt!
|
||||
|
||||
```python
|
||||
import sys
|
||||
from PyQt4 import QtGui
|
||||
|
||||
def window():
|
||||
# Création de l'objet application
|
||||
app = QtGui.QApplication(sys.argv)
|
||||
# Création d'un widget où notre label sera placé
|
||||
w = QtGui.QWidget()
|
||||
# Ajout d'un label au widget
|
||||
b = QtGui.QLabel(w)
|
||||
# Assignation de texte au label
|
||||
b.setText("Hello World!")
|
||||
# Assignation des tailles et des informations de placement
|
||||
w.setGeometry(100, 100, 200, 50)
|
||||
b.move(50, 20)
|
||||
# Assignation d'un nom à notre fenêtre
|
||||
w.setWindowTitle("PyQt")
|
||||
# Affichage de la fenêtre
|
||||
w.show()
|
||||
# Exécution de l'application
|
||||
sys.exit(app.exec_())
|
||||
|
||||
if __name__ == '__main__':
|
||||
window()
|
||||
|
||||
```
|
||||
|
||||
Pour obtenir certaines des fonctionnalités les plus avancées de **pyqt** nous devons commencer par chercher à construire des éléments supplémentaires.
|
||||
Ici nous voyons comment introduire une boîte de dialogue popup, utile pour demander une confirmation à un utilisateur ou fournir des informations.
|
||||
|
||||
```Python
|
||||
import sys
|
||||
from PyQt4.QtGui import *
|
||||
from PyQt4.QtCore import *
|
||||
|
||||
|
||||
def window():
|
||||
app = QApplication(sys.argv)
|
||||
w = QWidget()
|
||||
# Creation d'un bouton attaché au widget w
|
||||
b = QPushButton(w)
|
||||
b.setText("Press me")
|
||||
b.move(50, 50)
|
||||
# Dire à b d'appeler cette fonction quand il est cliqué
|
||||
# remarquez l'absence de "()" sur l'appel de la fonction
|
||||
b.clicked.connect(showdialog)
|
||||
w.setWindowTitle("PyQt Dialog")
|
||||
w.show()
|
||||
sys.exit(app.exec_())
|
||||
|
||||
# Cette fonction devrait créer une fenêtre de dialogue avec un bouton
|
||||
# qui attend d'être cliqué puis quitte le programme
|
||||
def showdialog():
|
||||
d = QDialog()
|
||||
b1 = QPushButton("ok", d)
|
||||
b1.move(50, 50)
|
||||
d.setWindowTitle("Dialog")
|
||||
# Cette modalité dit au popup de bloquer le parent pendant qu'il est actif
|
||||
d.setWindowModality(Qt.ApplicationModal)
|
||||
# En cliquant je voudrais que tout le processus se termine
|
||||
b1.clicked.connect(sys.exit)
|
||||
d.exec_()
|
||||
|
||||
if __name__ == '__main__':
|
||||
window()
|
||||
```
|
@ -34,7 +34,7 @@ let myFloat = 3.14
|
||||
let myString = "hello" // note that no types needed
|
||||
|
||||
// ------ 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.
|
||||
let oneToFive = 1 :: twoToFive // :: creates list with new 1st element
|
||||
// The result is [1; 2; 3; 4; 5]
|
||||
@ -53,7 +53,8 @@ add 2 3 // Now run the function.
|
||||
|
||||
// to define a multiline function, just use indents. No semicolons needed.
|
||||
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. Note
|
||||
// that equality operator is single char "=".
|
||||
List.filter isEven list // List.filter is a library function
|
||||
// with two parameters: a boolean function
|
||||
// and a list to work on
|
||||
@ -306,7 +307,7 @@ module DataTypeExamples =
|
||||
|
||||
// ------------------------------------
|
||||
// Union types (aka variants) have a set of choices
|
||||
// Only case can be valid at a time.
|
||||
// Only one case can be valid at a time.
|
||||
// ------------------------------------
|
||||
|
||||
// Use "type" with bar/pipe to define a union type
|
||||
|
@ -26,11 +26,11 @@ Version control is a system that records changes to a file(s), over time.
|
||||
|
||||
### Centralized Versioning vs. Distributed Versioning
|
||||
|
||||
* Centralized version control focuses on synchronizing, tracking, and backing
|
||||
* Centralized version control focuses on synchronizing, tracking, and backing
|
||||
up files.
|
||||
* Distributed version control focuses on sharing changes. Every change has a
|
||||
* Distributed version control focuses on sharing changes. Every change has a
|
||||
unique id.
|
||||
* Distributed systems have no defined structure. You could easily have a SVN
|
||||
* Distributed systems have no defined structure. You could easily have a SVN
|
||||
style, centralized system, with git.
|
||||
|
||||
[Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
|
||||
@ -57,7 +57,7 @@ A git repository is comprised of the .git directory & working tree.
|
||||
|
||||
### .git Directory (component of repository)
|
||||
|
||||
The .git directory contains all the configurations, logs, branches, HEAD, and
|
||||
The .git directory contains all the configurations, logs, branches, HEAD, and
|
||||
more.
|
||||
[Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
|
||||
|
||||
@ -68,15 +68,15 @@ referred to as your working directory.
|
||||
|
||||
### Index (component of .git dir)
|
||||
|
||||
The Index is the staging area in git. It's basically a layer that separates
|
||||
your working tree from the Git repository. This gives developers more power
|
||||
The Index is the staging area in git. It's basically a layer that separates
|
||||
your working tree from the Git repository. This gives developers more power
|
||||
over what gets sent to the Git repository.
|
||||
|
||||
### Commit
|
||||
|
||||
A git commit is a snapshot of a set of changes, or manipulations to your
|
||||
Working Tree. For example, if you added 5 files, and removed 2 others, these
|
||||
changes will be contained in a commit (or snapshot). This commit can then be
|
||||
A git commit is a snapshot of a set of changes, or manipulations to your
|
||||
Working Tree. For example, if you added 5 files, and removed 2 others, these
|
||||
changes will be contained in a commit (or snapshot). This commit can then be
|
||||
pushed to other repositories, or not!
|
||||
|
||||
### Branch
|
||||
@ -91,13 +91,13 @@ functionality to mark release points (v1.0, and so on)
|
||||
|
||||
### HEAD and head (component of .git dir)
|
||||
|
||||
HEAD is a pointer that points to the current branch. A repository only has 1
|
||||
*active* HEAD.
|
||||
head is a pointer that points to any commit. A repository can have any number
|
||||
HEAD is a pointer that points to the current branch. A repository only has 1
|
||||
*active* HEAD.
|
||||
head is a pointer that points to any commit. A repository can have any number
|
||||
of heads.
|
||||
|
||||
### Stages of Git
|
||||
* Modified - Changes have been made to a file but file has not been committed
|
||||
* Modified - Changes have been made to a file but file has not been committed
|
||||
to Git Database yet
|
||||
* Staged - Marks a modified file to go into your next commit snapshot
|
||||
* Committed - Files have been committed to the Git Database
|
||||
@ -111,7 +111,7 @@ to Git Database yet
|
||||
|
||||
### init
|
||||
|
||||
Create an empty Git repository. The Git repository's settings, stored
|
||||
Create an empty Git repository. The Git repository's settings, stored
|
||||
information, and more is stored in a directory (a folder) named ".git".
|
||||
|
||||
```bash
|
||||
@ -179,7 +179,7 @@ $ git help status
|
||||
|
||||
### add
|
||||
|
||||
To add files to the staging area/index. If you do not `git add` new files to
|
||||
To add files to the staging area/index. If you do not `git add` new files to
|
||||
the staging area/index, they will not be included in commits!
|
||||
|
||||
```bash
|
||||
@ -201,7 +201,7 @@ working directory/repo.
|
||||
|
||||
### branch
|
||||
|
||||
Manage your branches. You can view, edit, create, delete branches using this
|
||||
Manage your branches. You can view, edit, create, delete branches using this
|
||||
command.
|
||||
|
||||
```bash
|
||||
@ -250,7 +250,7 @@ $ git push origin --tags
|
||||
|
||||
### checkout
|
||||
|
||||
Updates all files in the working tree to match the version in the index, or
|
||||
Updates all files in the working tree to match the version in the index, or
|
||||
specified tree.
|
||||
|
||||
```bash
|
||||
@ -269,7 +269,7 @@ $ git checkout -b newBranch
|
||||
### clone
|
||||
|
||||
Clones, or copies, an existing repository into a new directory. It also adds
|
||||
remote-tracking branches for each branch in the cloned repo, which allows you
|
||||
remote-tracking branches for each branch in the cloned repo, which allows you
|
||||
to push to a remote branch.
|
||||
|
||||
```bash
|
||||
@ -285,7 +285,7 @@ $ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git -
|
||||
|
||||
### commit
|
||||
|
||||
Stores the current contents of the index in a new "commit." This commit
|
||||
Stores the current contents of the index in a new "commit." This commit
|
||||
contains the changes made and a message created by the user.
|
||||
|
||||
```bash
|
||||
@ -401,11 +401,11 @@ Pulls from a repository and merges it with another branch.
|
||||
$ git pull origin master
|
||||
|
||||
# By default, git pull will update your current branch
|
||||
# by merging in new changes from its remote-tracking branch
|
||||
# by merging in new changes from its remote-tracking branch
|
||||
$ git pull
|
||||
|
||||
# Merge in changes from remote branch and rebase
|
||||
# branch commits onto your local repo, like: "git fetch <remote> <branch>, git
|
||||
# branch commits onto your local repo, like: "git fetch <remote> <branch>, git
|
||||
# rebase <remote>/<branch>"
|
||||
$ git pull origin master --rebase
|
||||
```
|
||||
@ -421,7 +421,7 @@ Push and merge changes from a branch to a remote & branch.
|
||||
$ git push origin master
|
||||
|
||||
# By default, git push will push and merge changes from
|
||||
# the current branch to its remote-tracking branch
|
||||
# the current branch to its remote-tracking branch
|
||||
$ git push
|
||||
|
||||
# To link up current local branch with a remote branch, add -u flag:
|
||||
@ -432,7 +432,7 @@ $ git push
|
||||
|
||||
### stash
|
||||
|
||||
Stashing takes the dirty state of your working directory and saves it on a
|
||||
Stashing takes the dirty state of your working directory and saves it on a
|
||||
stack of unfinished changes that you can reapply at any time.
|
||||
|
||||
Let's say you've been doing some work in your git repo, but you want to pull
|
||||
@ -464,7 +464,7 @@ nothing to commit, working directory clean
|
||||
```
|
||||
|
||||
You can see what "hunks" you've stashed so far using `git stash list`.
|
||||
Since the "hunks" are stored in a Last-In-First-Out stack, our most recent
|
||||
Since the "hunks" are stored in a Last-In-First-Out stack, our most recent
|
||||
change will be at top.
|
||||
|
||||
```bash
|
||||
@ -495,7 +495,7 @@ Now you're ready to get back to work on your stuff!
|
||||
|
||||
### rebase (caution)
|
||||
|
||||
Take all changes that were committed on one branch, and replay them onto
|
||||
Take all changes that were committed on one branch, and replay them onto
|
||||
another branch.
|
||||
*Do not rebase commits that you have pushed to a public repo*.
|
||||
|
||||
@ -510,7 +510,7 @@ $ git rebase master experimentBranch
|
||||
### reset (caution)
|
||||
|
||||
Reset the current HEAD to the specified state. This allows you to undo merges,
|
||||
pulls, commits, adds, and more. It's a great command but also dangerous if you
|
||||
pulls, commits, adds, and more. It's a great command but also dangerous if you
|
||||
don't know what you are doing.
|
||||
|
||||
```bash
|
||||
@ -535,7 +535,7 @@ $ git reset --hard 31f2bb1
|
||||
Reflog will list most of the git commands you have done for a given time period,
|
||||
default 90 days.
|
||||
|
||||
This give you the chance to reverse any git commands that have gone wrong
|
||||
This give you the chance to reverse any git commands that have gone wrong
|
||||
(for instance, if a rebase has broken your application).
|
||||
|
||||
You can do this:
|
||||
@ -558,8 +558,8 @@ ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748)
|
||||
|
||||
### 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
|
||||
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
|
||||
@ -604,3 +604,5 @@ $ git rm /pather/to/the/file/HelloWorld.c
|
||||
* [Pro Git](http://www.git-scm.com/book/en/v2)
|
||||
|
||||
* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
|
||||
|
||||
* [The New Boston tutorial to Git covering basic commands and workflow](https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAKWClAD_iKpNC0bGHxGhcx)
|
||||
|
@ -15,15 +15,15 @@ contributors:
|
||||
---
|
||||
|
||||
Go was created out of the need to get work done. It's not the latest trend
|
||||
in computer science, but it is the newest fastest way to solve real-world
|
||||
in programming language theory, but it is a way to solve real-world
|
||||
problems.
|
||||
|
||||
It has familiar concepts of imperative languages with static typing.
|
||||
It draws concepts from imperative languages with static typing.
|
||||
It's fast to compile and fast to execute, it adds easy-to-understand
|
||||
concurrency to leverage today's multi-core CPUs, and has features to
|
||||
help with large-scale programming.
|
||||
concurrency because multi-core CPUs are now common, and it's used successfully
|
||||
in large codebases (~100 million loc at Google, Inc.).
|
||||
|
||||
Go comes with a great standard library and an enthusiastic community.
|
||||
Go comes with a good standard library and a sizeable community.
|
||||
|
||||
```go
|
||||
// Single line comment
|
||||
@ -48,7 +48,7 @@ import (
|
||||
// executable program. Love it or hate it, Go uses brace brackets.
|
||||
func main() {
|
||||
// Println outputs a line to stdout.
|
||||
// Qualify it with the package name, fmt.
|
||||
// It comes from the package fmt.
|
||||
fmt.Println("Hello world!")
|
||||
|
||||
// Call another function within this package.
|
||||
@ -180,7 +180,7 @@ func learnFlowControl() {
|
||||
if true {
|
||||
fmt.Println("told ya")
|
||||
}
|
||||
// Formatting is standardized by the command line command "go fmt."
|
||||
// Formatting is standardized by the command line command "go fmt".
|
||||
if false {
|
||||
// Pout.
|
||||
} else {
|
||||
@ -277,7 +277,8 @@ func sentenceFactory(mystring string) func(before, after string) string {
|
||||
}
|
||||
|
||||
func learnDefer() (ok bool) {
|
||||
// Deferred statements are executed just before the function returns.
|
||||
// A defer statement pushes a function call onto a list. The list of saved
|
||||
// calls is executed AFTER the surrounding function returns.
|
||||
defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
|
||||
defer fmt.Println("\nThis line is being printed first because")
|
||||
// Defer is commonly used to close a file, so the function closing the
|
||||
|
@ -124,6 +124,9 @@ last [1..5] -- 5
|
||||
fst ("haskell", 1) -- "haskell"
|
||||
snd ("haskell", 1) -- 1
|
||||
|
||||
-- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc)
|
||||
snd ("snd", "can't touch this", "da na na na") -- error! see function below
|
||||
|
||||
----------------------------------------------------
|
||||
-- 3. Functions
|
||||
----------------------------------------------------
|
||||
@ -159,8 +162,8 @@ fib 1 = 1
|
||||
fib 2 = 2
|
||||
fib x = fib (x - 1) + fib (x - 2)
|
||||
|
||||
-- Pattern matching on tuples:
|
||||
foo (x, y) = (x + 1, y + 2)
|
||||
-- Pattern matching on tuples
|
||||
sndOfTriple (_, y, _) = y -- use a wild card (_) to bypass naming unused value
|
||||
|
||||
-- Pattern matching on lists. Here `x` is the first element
|
||||
-- in the list, and `xs` is the rest of the list. We can write
|
||||
@ -203,11 +206,11 @@ foo = (4*) . (10+)
|
||||
foo 5 -- 60
|
||||
|
||||
-- fixing precedence
|
||||
-- Haskell has an operator called `$`. This operator applies a function
|
||||
-- to a given parameter. In contrast to standard function application, which
|
||||
-- has highest possible priority of 10 and is left-associative, the `$` operator
|
||||
-- Haskell has an operator called `$`. This operator applies a function
|
||||
-- to a given parameter. In contrast to standard function application, which
|
||||
-- has highest possible priority of 10 and is left-associative, the `$` operator
|
||||
-- has priority of 0 and is right-associative. Such a low priority means that
|
||||
-- the expression on its right is applied as the parameter to the function on its left.
|
||||
-- the expression on its right is applied as a parameter to the function on its left.
|
||||
|
||||
-- before
|
||||
even (fib 7) -- false
|
||||
@ -223,7 +226,7 @@ even . fib $ 7 -- false
|
||||
-- 5. Type signatures
|
||||
----------------------------------------------------
|
||||
|
||||
-- Haskell has a very strong type system, and every valid expression has a type.
|
||||
-- Haskell has a very strong type system, and every valid expression has a type.
|
||||
|
||||
-- Some basic types:
|
||||
5 :: Integer
|
||||
|
@ -770,19 +770,18 @@ class UsingExample {
|
||||
```
|
||||
|
||||
We're still only scratching the surface here of what Haxe can do. For a formal
|
||||
overview of all Haxe features, checkout the [online
|
||||
manual](http://haxe.org/manual), the [online API](http://api.haxe.org/), and
|
||||
"haxelib", the [haxe library repo] (http://lib.haxe.org/).
|
||||
overview of all Haxe features, see the [manual](https://haxe.org/manual) and
|
||||
the [API docs](https://api.haxe.org/). For a comprehensive directory of available
|
||||
third-party Haxe libraries, see [Haxelib](https://lib.haxe.org/).
|
||||
|
||||
For more advanced topics, consider checking out:
|
||||
|
||||
* [Abstract types](http://haxe.org/manual/abstracts)
|
||||
* [Macros](http://haxe.org/manual/macros), and [Compiler Macros](http://haxe.org/manual/macros_compiler)
|
||||
* [Tips and Tricks](http://haxe.org/manual/tips_and_tricks)
|
||||
|
||||
|
||||
Finally, please join us on [the mailing list](https://groups.google.com/forum/#!forum/haxelang), on IRC [#haxe on
|
||||
freenode](http://webchat.freenode.net/), or on
|
||||
[Google+](https://plus.google.com/communities/103302587329918132234).
|
||||
* [Abstract types](https://haxe.org/manual/types-abstract.html)
|
||||
* [Macros](https://haxe.org/manual/macro.html)
|
||||
* [Compiler Features](https://haxe.org/manual/cr-features.html)
|
||||
|
||||
|
||||
Finally, please join us on [the Haxe forum](https://community.haxe.org/),
|
||||
on IRC [#haxe on
|
||||
freenode](http://webchat.freenode.net/), or on the
|
||||
[Haxe Gitter chat](https://gitter.im/HaxeFoundation/haxe).
|
||||
|
1
hre.csv
Normal file
1
hre.csv
Normal file
@ -0,0 +1 @@
|
||||
Ix,Dynasty,Name,Birth,Death,Coronation 1,Coronation 2,Ceased to be Emperor
N/A,Carolingian,Charles I,2 April 742,28 January 814,25 December 800,N/A,28 January 814
N/A,Carolingian,Louis I,778,20 June 840,11 September 813,5 October 816,20 June 840
N/A,Carolingian,Lothair I,795,29 September 855,5 April 823,N/A,29 September 855
N/A,Carolingian,Louis II,825,12 August 875,15 June 844,18 May 872,12 August 875
N/A,Carolingian,Charles II,13 June 823,6 October 877,29 December 875,N/A,6 October 877
N/A,Carolingian,Charles III,13 June 839,13 January 888,12 February 881,N/A,11 November 887
N/A,Widonid,Guy III,835,12 December 894,21 February 891,N/A,12 December 894
N/A,Widonid,Lambert I,880,15 October 898,30 April 892,N/A,15 October 898
N/A,Carolingian,Arnulph,850,8 December 899,22 February 896,N/A,8 December 899
N/A,Bosonid,Louis III,880,5 June 928,22 February 901,N/A,21 July 905
N/A,Unruoching,Berengar I,845,7 April 924,December 915,N/A,7 April 924
1,Ottonian,Otto I,23 November 912,7 May 973,2 February 962,N/A,7 May 973
2,Ottonian,Otto II,955,7 December 983,25 December 967,N/A,7 December 983
3,Ottonian,Otto III,980,23 January 1002,21 May 996,N/A,23 January 1002
4,Ottonian,Henry II,6 May 973,13 July 1024,14 February 1014,N/A,13 July 1024
5,Salian,Conrad II,990,4 June 1039,26 March 1027,N/A,4 June 1039
6,Salian,Henry III,29 October 1017,5 October 1056,25 December 1046,N/A,5 October 1056
7,Salian,Henry IV,11 November 1050,7 August 1106,31 March 1084,N/A,December 1105
8,Salian,Henry V,8 November 1086,23 May 1125,13 April 1111,N/A,23 May 1125
9,Supplinburg,Lothair III,9 June 1075,4 December 1137,4 June 1133,N/A,4 December 1137
10,Staufen,Frederick I,1122,10 June 1190,18 June 1155,N/A,10 June 1190
11,Staufen,Henry VI,November 1165,28 September 1197,14 April 1191,N/A,28 September 1197
12,Welf,Otto IV,1175,19 May 1218,4 October 1209,N/A,1215
13,Staufen,Frederick II,26 December 1194,13 December 1250,22 November 1220,N/A,13 December 1250
14,Luxembourg,Henry VII,1275,24 August 1313,29 June 1312,N/A,24 August 1313
15,Wittelsbach,Louis IV,1 April 1282,11 October 1347,17 January 1328,N/A,11 October 1347
16,Luxembourg,Charles IV,14 May 1316,29 November 1378,5 April 1355,N/A,29 November 1378
17,Luxembourg,Sigismund,14 February 1368,9 December 1437,31 May 1433,N/A,9 December 1437
18,Habsburg,Frederick III,21 September 1415,19 August 1493,19 March 1452,N/A,19 August 1493
19,Habsburg,Maximilian I,22 March 1459,12 January 1519,N/A,N/A,12 January 1519
20,Habsburg,Charles V,24 February 1500,21 September 1558,February 1530,N/A,16 January 1556
21,Habsburg,Ferdinand I,10 March 1503,25 July 1564,N/A,N/A,25 July 1564
22,Habsburg,Maximilian II,31 July 1527,12 October 1576,N/A,N/A,12 October 1576
23,Habsburg,Rudolph II,18 July 1552,20 January 1612,30 June 1575,N/A,20 January 1612
24,Habsburg,Matthias,24 February 1557,20 March 1619,23 January 1612,N/A,20 March 1619
25,Habsburg,Ferdinand II,9 July 1578,15 February 1637,10 March 1619,N/A,15 February 1637
26,Habsburg,Ferdinand III,13 July 1608,2 April 1657,18 November 1637,N/A,2 April 1657
27,Habsburg,Leopold I,9 June 1640,5 May 1705,6 March 1657,N/A,5 May 1705
28,Habsburg,Joseph I,26 July 1678,17 April 1711,1 May 1705,N/A,17 April 1711
29,Habsburg,Charles VI,1 October 1685,20 October 1740,22 December 1711,N/A,20 October 1740
30,Wittelsbach,Charles VII,6 August 1697,20 January 1745,12 February 1742,N/A,20 January 1745
31,Lorraine,Francis I,8 December 1708,18 August 1765,N/A,N/A,18 August 1765
32,Habsburg-Lorraine,Joseph II,13 March 1741,20 February 1790,19 August 1765,N/A,20 February 1790
33,Habsburg-Lorraine,Leopold II,5 May 1747,1 March 1792,N/A,N/A,1 March 1792
34,Habsburg-Lorraine,Francis II,12 February 1768,2 March 1835,4 March 1792,N/A,6 August 1806
|
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: html
|
||||
filename: learnhtml.html
|
||||
filename: learnhtml.txt
|
||||
contributors:
|
||||
- ["Christophe THOMAS", "https://github.com/WinChris"]
|
||||
translators:
|
||||
|
816
hu-hu/python-hu.html.markdown
Normal file
816
hu-hu/python-hu.html.markdown
Normal file
@ -0,0 +1,816 @@
|
||||
---
|
||||
language: python
|
||||
contributors:
|
||||
- ["Louie Dinh", "http://ldinh.ca"]
|
||||
- ["Amin Bandali", "https://aminb.org"]
|
||||
- ["Andre Polykanine", "https://github.com/Oire"]
|
||||
- ["evuez", "http://github.com/evuez"]
|
||||
- ["asyne", "https://github.com/justblah"]
|
||||
- ["habi", "http://github.com/habi"]
|
||||
translators:
|
||||
- ["Tamás Diószegi", "https://github.com/ditam"]
|
||||
filename: learnpython-hu.py
|
||||
lang: hu-hu
|
||||
---
|
||||
|
||||
A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az
|
||||
egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem
|
||||
bele. Tulajdonképpen futtatható pszeudokód.
|
||||
|
||||
Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh)
|
||||
vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen.
|
||||
|
||||
Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve
|
||||
általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz
|
||||
támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az
|
||||
ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/)
|
||||
ajánlott.
|
||||
|
||||
Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x
|
||||
verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával.
|
||||
A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami
|
||||
Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott.
|
||||
|
||||
```python
|
||||
|
||||
# Az egysoros kommentek kettőskereszttel kezdődnek
|
||||
|
||||
""" Többsoros stringeket három darab " közé
|
||||
fogva lehet írni, ezeket gyakran használják
|
||||
több soros kommentként.
|
||||
"""
|
||||
|
||||
####################################################
|
||||
# 1. Egyszerű adattípusok és operátorok
|
||||
####################################################
|
||||
|
||||
# Használhatsz számokat
|
||||
3 # => 3
|
||||
|
||||
# Az alapműveletek meglepetésektől mentesek
|
||||
1 + 1 # => 2
|
||||
8 - 1 # => 7
|
||||
10 * 2 # => 20
|
||||
35 / 5 # => 7
|
||||
|
||||
# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része
|
||||
# lesz az eredmény
|
||||
5 / 2 # => 2
|
||||
|
||||
# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk
|
||||
2.0 # Ez egy float
|
||||
11.0 / 4.0 # => 2.75 áh... máris jobb
|
||||
|
||||
# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi
|
||||
5 // 3 # => 1
|
||||
5.0 // 3.0 # => 1.0 # floatok esetén is
|
||||
-5 // 3 # => -2
|
||||
-5.0 // 3.0 # => -2.0
|
||||
|
||||
# Ha importáljuk a division modult (ld. 6. Modulok rész),
|
||||
# akkor a '/' jellel pontos osztást tudunk végezni.
|
||||
from __future__ import division
|
||||
|
||||
11 / 4 # => 2.75 ...sima osztás
|
||||
11 // 4 # => 2 ...egész osztás
|
||||
|
||||
# Modulo művelet
|
||||
7 % 3 # => 1
|
||||
|
||||
# Hatványozás (x az y. hatványra)
|
||||
2 ** 4 # => 16
|
||||
|
||||
# A precedencia zárójelekkel befolyásolható
|
||||
(1 + 3) * 2 # => 8
|
||||
|
||||
# Logikai operátorok
|
||||
# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes
|
||||
True and False # => False
|
||||
False or True # => True
|
||||
|
||||
# A logikai operátorok egészeken is használhatóak
|
||||
0 and 2 # => 0
|
||||
-5 or 0 # => -5
|
||||
0 == False # => True
|
||||
2 == True # => False
|
||||
1 == True # => True
|
||||
|
||||
# Negálni a not kulcsszóval lehet
|
||||
not True # => False
|
||||
not False # => True
|
||||
|
||||
# Egyenlőségvizsgálat ==
|
||||
1 == 1 # => True
|
||||
2 == 1 # => False
|
||||
|
||||
# Egyenlőtlenség !=
|
||||
1 != 1 # => False
|
||||
2 != 1 # => True
|
||||
|
||||
# További összehasonlítások
|
||||
1 < 10 # => True
|
||||
1 > 10 # => False
|
||||
2 <= 2 # => True
|
||||
2 >= 2 # => True
|
||||
|
||||
# Az összehasonlítások láncolhatóak!
|
||||
1 < 2 < 3 # => True
|
||||
2 < 3 < 2 # => False
|
||||
|
||||
# Stringeket " vagy ' jelek közt lehet megadni
|
||||
"Ez egy string."
|
||||
'Ez egy másik string.'
|
||||
|
||||
# A stringek összeadhatóak!
|
||||
"Hello " + "world!" # => "Hello world!"
|
||||
# '+' jel nélkül is összeadhatóak
|
||||
"Hello " "world!" # => "Hello world!"
|
||||
|
||||
# ... illetve szorozhatóak
|
||||
"Hello" * 3 # => "HelloHelloHello"
|
||||
|
||||
# Kezelhető karakterek indexelhető listájaként
|
||||
"This is a string"[0] # => 'T'
|
||||
|
||||
# A string hosszát a len függvény adja meg
|
||||
len("This is a string") # => 16
|
||||
|
||||
# String formázáshoz a % jel használható
|
||||
# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog
|
||||
# kerülni, de azért jó tudni, hogyan működik.
|
||||
x = 'alma'
|
||||
y = 'citrom'
|
||||
z = "A kosárban levő elemek: %s és %s" % (x, y)
|
||||
|
||||
# A string formázás újabb módja a format metódus használatával történik.
|
||||
# Jelenleg ez a javasolt megoldás.
|
||||
"{} egy {} szöveg".format("Ez", "helytartó")
|
||||
"A {0} pedig {1}".format("string", "formázható")
|
||||
# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók.
|
||||
"{name} kedvence a {food}".format(name="Bob", food="lasagna")
|
||||
|
||||
# None egy objektum
|
||||
None # => None
|
||||
|
||||
# A None-nal való összehasonlításhoz ne használd a "==" jelet,
|
||||
# használd az "is" kulcsszót helyette
|
||||
"etc" is None # => False
|
||||
None is None # => True
|
||||
|
||||
# Az 'is' operátor objektum egyezést vizsgál.
|
||||
# Primitív típusok esetén ez nem túl hasznos,
|
||||
# objektumok esetén azonban annál inkább.
|
||||
|
||||
# Bármilyen objektum használható logikai kontextusban.
|
||||
# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek):
|
||||
# - None
|
||||
# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j)
|
||||
# - üres sorozatok (pl. '', (), [])
|
||||
# - üres konténerek (pl., {}, set())
|
||||
# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint,
|
||||
# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
|
||||
#
|
||||
# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki)
|
||||
bool(0) # => False
|
||||
bool("") # => False
|
||||
|
||||
|
||||
####################################################
|
||||
# 2. Változók és kollekciók
|
||||
####################################################
|
||||
|
||||
# Létezik egy print utasítás
|
||||
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
|
||||
|
||||
# Így lehet egyszerűen bemenetet kérni a konzolról:
|
||||
input_string_var = raw_input(
|
||||
"Enter some data: ") # Visszatér a megadott stringgel
|
||||
input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként
|
||||
# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni
|
||||
# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve
|
||||
|
||||
# A változókat nem szükséges a használat előtt deklarálni
|
||||
some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas
|
||||
some_var # => 5
|
||||
|
||||
# Érték nélküli változóra hivatkozás hibát dob.
|
||||
# Lásd a Control Flow szekciót a kivételkezelésről.
|
||||
some_other_var # name error hibát dob
|
||||
|
||||
# az if használható kifejezésként
|
||||
# a C nyelv '?:' ternáris operátorával egyenértékűen
|
||||
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
|
||||
|
||||
# A listákban sorozatok tárolhatóak
|
||||
li = []
|
||||
# Már inicializáláskor megadhatóak elemek
|
||||
other_li = [4, 5, 6]
|
||||
|
||||
# A lista végére az append metódus rak új elemet
|
||||
li.append(1) # li jelenleg [1]
|
||||
li.append(2) # li jelenleg [1, 2]
|
||||
li.append(4) # li jelenleg [1, 2, 4]
|
||||
li.append(3) # li jelenleg [1, 2, 4, 3]
|
||||
# A végéről a pop metódus távolít el elemet
|
||||
li.pop() # => 3 és li jelenleg [1, 2, 4]
|
||||
# Rakjuk vissza
|
||||
li.append(3) # li jelenleg [1, 2, 4, 3], újra.
|
||||
|
||||
# A lista elemeket tömb indexeléssel lehet hivatkozni
|
||||
li[0] # => 1
|
||||
# A már inicializált értékekhez a = jellel lehet új értéket rendelni
|
||||
li[0] = 42
|
||||
li[0] # => 42
|
||||
li[0] = 1 # csak visszaállítjuk az eredeti értékére
|
||||
# Így is lehet az utolsó elemre hivatkozni
|
||||
li[-1] # => 3
|
||||
|
||||
# A túlindexelés eredménye IndexError
|
||||
li[4] # IndexError hibát dob
|
||||
|
||||
# A lista részeit a slice szintaxissal lehet kimetszeni
|
||||
# (Matekosoknak ez egy zárt/nyitott intervallum.)
|
||||
li[1:3] # => [2, 4]
|
||||
# A lista eleje kihagyható így
|
||||
li[2:] # => [4, 3]
|
||||
# Kihagyható a vége
|
||||
li[:3] # => [1, 2, 4]
|
||||
# Minden második elem kiválasztása
|
||||
li[::2] # =>[1, 4]
|
||||
# A lista egy másolata, fordított sorrendben
|
||||
li[::-1] # => [3, 4, 2, 1]
|
||||
# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek
|
||||
# li[start:end:step]
|
||||
|
||||
# Listaelemek a "del" paranccsal törölhetőek
|
||||
del li[2] # li jelenleg [1, 2, 3]
|
||||
|
||||
# A listák összeadhatóak
|
||||
li + other_li # => [1, 2, 3, 4, 5, 6]
|
||||
# Megjegyzés: az eredeti li és other_li értékei változatlanok
|
||||
|
||||
# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal
|
||||
li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6]
|
||||
|
||||
# Egy elem első előfordulásának eltávolítása
|
||||
li.remove(2) # li jelenleg [1, 3, 4, 5, 6]
|
||||
li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában
|
||||
|
||||
# Elemek beszúrhatóak tetszőleges helyre
|
||||
li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét
|
||||
|
||||
# Egy elem első előfordulási helye
|
||||
li.index(2) # => 1
|
||||
li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában
|
||||
|
||||
# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető
|
||||
1 in li # => True
|
||||
|
||||
# A lista hossza a "len()" függvénnyel
|
||||
len(li) # => 6
|
||||
|
||||
# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak
|
||||
tup = (1, 2, 3)
|
||||
tup[0] # => 1
|
||||
tup[0] = 3 # TypeError hibát dob
|
||||
|
||||
# Az összes lista-műveletet ezeken is használható
|
||||
len(tup) # => 3
|
||||
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
|
||||
tup[:2] # => (1, 2)
|
||||
2 in tup # => True
|
||||
|
||||
# Az N-esek (és listák) kicsomagolhatóak külön változókba
|
||||
a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3
|
||||
d, e, f = 4, 5, 6 # a zárójel elhagyható
|
||||
# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik
|
||||
g = 4, 5, 6 # => (4, 5, 6)
|
||||
# Nézd, milyen egyszerű két értéket megcserélni
|
||||
e, d = d, e # d most már 5 és az e 4
|
||||
|
||||
# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók
|
||||
empty_dict = {}
|
||||
# Ez pedig rögtön értékekkel van inicializálva
|
||||
filled_dict = {"one": 1, "two": 2, "three": 3}
|
||||
|
||||
# Egy dictionary értékei [] jelek közt indexelhetőek
|
||||
filled_dict["one"] # => 1
|
||||
|
||||
# A "keys()" metódus visszatér a kulcsok listájával
|
||||
filled_dict.keys() # => ["three", "two", "one"]
|
||||
# Megjegyzés: egy dictionary párjainak sorrendje nem garantált
|
||||
# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket.
|
||||
|
||||
# Az értékek listája a "values()" metódussal kérhető le
|
||||
filled_dict.values() # => [3, 2, 1]
|
||||
# ld. a fenti megjegyzést az elemek sorrendjéről.
|
||||
|
||||
# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal
|
||||
filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]
|
||||
|
||||
# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben
|
||||
"one" in filled_dict # => True
|
||||
1 in filled_dict # => False
|
||||
|
||||
# Nem létező kulcs hivatkozása KeyError hibát dob
|
||||
filled_dict["four"] # KeyError
|
||||
|
||||
# A "get()" metódus használatával elkerülhető a KeyError
|
||||
filled_dict.get("one") # => 1
|
||||
filled_dict.get("four") # => None
|
||||
# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén
|
||||
filled_dict.get("one", 4) # => 1
|
||||
filled_dict.get("four", 4) # => 4
|
||||
# Megjegyzés: ettől még filled_dict.get("four") => None
|
||||
# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben)
|
||||
|
||||
# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek:
|
||||
filled_dict["four"] = 4 # ez után filled_dict["four"] => 4
|
||||
|
||||
# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva
|
||||
filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re
|
||||
filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5
|
||||
|
||||
# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat
|
||||
empty_set = set()
|
||||
# Inicializáljuk ezt a halmazt néhány elemmel
|
||||
some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4])
|
||||
|
||||
# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet
|
||||
another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4])
|
||||
|
||||
# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni
|
||||
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
|
||||
|
||||
# Új halmaz-elemek hozzáadása
|
||||
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
|
||||
|
||||
# Halmaz metszés a & operátorral
|
||||
other_set = {3, 4, 5, 6}
|
||||
filled_set & other_set # => {3, 4, 5}
|
||||
|
||||
# Halmaz unió | operátorral
|
||||
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
|
||||
|
||||
# Halmaz különbség -
|
||||
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
|
||||
|
||||
# Szimmetrikus differencia ^
|
||||
{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
|
||||
|
||||
# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit
|
||||
{1, 2} >= {1, 2, 3} # => False
|
||||
|
||||
# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak
|
||||
{1, 2} <= {1, 2, 3} # => True
|
||||
|
||||
# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható
|
||||
2 in filled_set # => True
|
||||
10 in filled_set # => False
|
||||
|
||||
|
||||
####################################################
|
||||
# 3. Control Flow
|
||||
####################################################
|
||||
|
||||
# Legyen egy változónk
|
||||
some_var = 5
|
||||
|
||||
# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben!
|
||||
# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél"
|
||||
if some_var > 10:
|
||||
print "some_var nagyobb, mint 10."
|
||||
elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben.
|
||||
print "some_var kisebb 10-nél"
|
||||
else: # Ez sem kötelező.
|
||||
print "some_var kereken 10."
|
||||
|
||||
"""
|
||||
For ciklusokkal végigiterálhatunk listákon
|
||||
a kimenet:
|
||||
A(z) kutya emlős
|
||||
A(z) macska emlős
|
||||
A(z) egér emlős
|
||||
"""
|
||||
for animal in ["kutya", "macska", "egér"]:
|
||||
# A {0} kifejezéssel formázzuk a stringet, ld. korábban.
|
||||
print "A(z) {0} emlős".format(animal)
|
||||
|
||||
"""
|
||||
"range(number)" visszatér számok listájával 0-től number-ig
|
||||
a kimenet:
|
||||
0
|
||||
1
|
||||
2
|
||||
3
|
||||
"""
|
||||
for i in range(4):
|
||||
print i
|
||||
|
||||
"""
|
||||
"range(lower, upper)" visszatér a lower és upper közti számok listájával
|
||||
a kimenet:
|
||||
4
|
||||
5
|
||||
6
|
||||
7
|
||||
"""
|
||||
for i in range(4, 8):
|
||||
print i
|
||||
|
||||
"""
|
||||
A while ciklus a feltétel hamissá válásáig fut.
|
||||
a kimenet:
|
||||
0
|
||||
1
|
||||
2
|
||||
3
|
||||
"""
|
||||
x = 0
|
||||
while x < 4:
|
||||
print x
|
||||
x += 1 # Rövidítés az x = x + 1 kifejezésre
|
||||
|
||||
# A kivételek try/except blokkokkal kezelhetőek
|
||||
|
||||
# Python 2.6-tól felfele:
|
||||
try:
|
||||
# A "raise" szóval lehet hibát dobni
|
||||
raise IndexError("Ez egy index error")
|
||||
except IndexError as e:
|
||||
pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat.
|
||||
except (TypeError, NameError):
|
||||
pass # Ha szükséges, egyszerre több hiba típus is kezelhető
|
||||
else: # Az except blokk után opcionálisan megadható
|
||||
print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák
|
||||
finally: # Mindenképpen lefut
|
||||
print "Itt felszabadíthatjuk az erőforrásokat például"
|
||||
|
||||
# Az erőforrások felszabadításához try/finally helyett a with használható
|
||||
with open("myfile.txt") as f:
|
||||
for line in f:
|
||||
print line
|
||||
|
||||
|
||||
####################################################
|
||||
# 4. Függvények
|
||||
####################################################
|
||||
|
||||
# A "def" szóval hozhatunk létre új függvényt
|
||||
def add(x, y):
|
||||
print "x is {0} and y is {1}".format(x, y)
|
||||
return x + y # A return szóval tudunk értékeket visszaadni
|
||||
|
||||
|
||||
# Így hívunk függvényt paraméterekkel
|
||||
add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11
|
||||
|
||||
# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt
|
||||
add(y=6, x=5) # Ez esetben a sorrendjük nem számít
|
||||
|
||||
|
||||
# Változó számú paramétert fogadó függvény így definiálható.
|
||||
# A * használatával a paramétereket egy N-esként kapjuk meg.
|
||||
def varargs(*args):
|
||||
return args
|
||||
|
||||
|
||||
varargs(1, 2, 3) # => (1, 2, 3)
|
||||
|
||||
|
||||
# Változó számú nevesített paramétert fogadó függvény is megadható,
|
||||
# a ** használatával a paramétereket egy dictionary-ként kapjuk meg
|
||||
def keyword_args(**kwargs):
|
||||
return kwargs
|
||||
|
||||
|
||||
# Nézzük meg, mi történik
|
||||
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
|
||||
|
||||
|
||||
# A két módszer egyszerre is használható
|
||||
def all_the_args(*args, **kwargs):
|
||||
print args
|
||||
print kwargs
|
||||
|
||||
|
||||
"""
|
||||
all_the_args(1, 2, a=3, b=4) kimenete:
|
||||
(1, 2)
|
||||
{"a": 3, "b": 4}
|
||||
"""
|
||||
|
||||
# Függvények hívásakor a fenti args és kwargs módszerek inverze használható
|
||||
# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe.
|
||||
args = (1, 2, 3, 4)
|
||||
kwargs = {"a": 3, "b": 4}
|
||||
all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4)
|
||||
all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4)
|
||||
all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4)
|
||||
|
||||
|
||||
# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek,
|
||||
# a * illetve ** operátorokkal kifejtve
|
||||
def pass_all_the_args(*args, **kwargs):
|
||||
all_the_args(*args, **kwargs)
|
||||
print varargs(*args)
|
||||
print keyword_args(**kwargs)
|
||||
|
||||
|
||||
# Függvény scope
|
||||
x = 5
|
||||
|
||||
|
||||
def set_x(num):
|
||||
# A lokális x változó nem ugyanaz, mint a globális x
|
||||
x = num # => 43
|
||||
print x # => 43
|
||||
|
||||
|
||||
def set_global_x(num):
|
||||
global x
|
||||
print x # => 5
|
||||
x = num # a globális x-et 6-ra állítjuk
|
||||
print x # => 6
|
||||
|
||||
|
||||
set_x(43)
|
||||
set_global_x(6)
|
||||
|
||||
|
||||
# A pythonban a függvény elsőrendű (ún. "first class") típus
|
||||
def create_adder(x):
|
||||
def adder(y):
|
||||
return x + y
|
||||
|
||||
return adder
|
||||
|
||||
|
||||
add_10 = create_adder(10)
|
||||
add_10(3) # => 13
|
||||
|
||||
# Névtelen függvények is definiálhatóak
|
||||
(lambda x: x > 2)(3) # => True
|
||||
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
|
||||
|
||||
# Léteznek beépített magasabb rendű függvények
|
||||
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
||||
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
|
||||
|
||||
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||
|
||||
# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel
|
||||
[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]
|
||||
|
||||
# halmaz és dictionary képzők is léteznek
|
||||
{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}
|
||||
{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
|
||||
|
||||
|
||||
####################################################
|
||||
# 5. Osztályok
|
||||
####################################################
|
||||
|
||||
# Az object osztály egy alosztályát képezzük
|
||||
class Human(object):
|
||||
# Osztály szintű mező: az osztály összes példányában azonos
|
||||
species = "H. sapiens"
|
||||
|
||||
# Ez a függvény meghívódik az osztály példányosításakor.
|
||||
# Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python
|
||||
# előre definiált, a nyelv által belsőleg használt, de a felhasználó által
|
||||
# is látható objektumok és mezők neveire.
|
||||
# Ne vezessünk be új, ilyen elnevezési sémát használó neveket!
|
||||
def __init__(self, name):
|
||||
# A paramétert értékül adjuk a példány name attribútumának
|
||||
self.name = name
|
||||
|
||||
# Inicializálunk egy mezőt
|
||||
self.age = 0
|
||||
|
||||
# Példány metódus. Minden metódus első paramétere a "self", a példány maga
|
||||
def say(self, msg):
|
||||
return "{0}: {1}".format(self.name, msg)
|
||||
|
||||
# Egy osztálymetódus az osztály összes példány közt meg van osztva.
|
||||
# Hívásukkor az első paraméter mindig a hívó osztály.
|
||||
@classmethod
|
||||
def get_species(cls):
|
||||
return cls.species
|
||||
|
||||
# Egy statikus metódus osztály és példányreferencia nélkül hívódik
|
||||
@staticmethod
|
||||
def grunt():
|
||||
return "*grunt*"
|
||||
|
||||
# Egy property jelölésű függvény olyan, mint egy getter.
|
||||
# Használatával az age mező egy csak-olvasható attribútummá válik.
|
||||
@property
|
||||
def age(self):
|
||||
return self._age
|
||||
|
||||
# Így lehet settert megadni egy mezőhöz
|
||||
@age.setter
|
||||
def age(self, age):
|
||||
self._age = age
|
||||
|
||||
# Így lehet egy mező törlését engedélyezni
|
||||
@age.deleter
|
||||
def age(self):
|
||||
del self._age
|
||||
|
||||
|
||||
# Példányosítsuk az osztályt
|
||||
i = Human(name="Ian")
|
||||
print i.say("hi") # kimenet: "Ian: hi"
|
||||
|
||||
j = Human("Joel")
|
||||
print j.say("hello") # kimenet: "Joel: hello"
|
||||
|
||||
# Hívjuk az osztály metódusunkat
|
||||
i.get_species() # => "H. sapiens"
|
||||
|
||||
# Változtassuk meg az osztály szintű attribútumot
|
||||
Human.species = "H. neanderthalensis"
|
||||
i.get_species() # => "H. neanderthalensis"
|
||||
j.get_species() # => "H. neanderthalensis"
|
||||
|
||||
# Hívjuk meg a statikus metódust
|
||||
Human.grunt() # => "*grunt*"
|
||||
|
||||
# Adjunk új értéket a mezőnek
|
||||
i.age = 42
|
||||
|
||||
# Kérjük le a mező értékét
|
||||
i.age # => 42
|
||||
|
||||
# Töröljük a mezőt
|
||||
del i.age
|
||||
i.age # => AttributeError hibát dob
|
||||
|
||||
####################################################
|
||||
# 6. Modulok
|
||||
####################################################
|
||||
|
||||
# Modulokat így lehet importálni
|
||||
import math
|
||||
|
||||
print math.sqrt(16) # => 4
|
||||
|
||||
# Lehetséges csak bizonyos függvényeket importálni egy modulból
|
||||
from math import ceil, floor
|
||||
|
||||
print ceil(3.7) # => 4.0
|
||||
print floor(3.7) # => 3.0
|
||||
|
||||
# Egy modul összes függvénye is importálható
|
||||
# Vigyázat: ez nem ajánlott.
|
||||
from math import *
|
||||
|
||||
# A modulok nevei lerövidíthetőek
|
||||
import math as m
|
||||
|
||||
math.sqrt(16) == m.sqrt(16) # => True
|
||||
# Meggyőződhetünk róla, hogy a függvények valóban azonosak
|
||||
from math import sqrt
|
||||
|
||||
math.sqrt == m.sqrt == sqrt # => True
|
||||
|
||||
# A Python modulok egyszerű fájlok.
|
||||
# Írhatsz sajátot és importálhatod is.
|
||||
# A modul neve azonos a tartalmazó fájl nevével.
|
||||
|
||||
# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul.
|
||||
import math
|
||||
|
||||
dir(math)
|
||||
|
||||
|
||||
# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos
|
||||
# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett.
|
||||
# A lokális mappa prioritást élvez a beépített könyvtárak felett.
|
||||
|
||||
|
||||
####################################################
|
||||
# 7. Haladóknak
|
||||
####################################################
|
||||
|
||||
# Generátorok
|
||||
# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket.
|
||||
|
||||
# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit,
|
||||
# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat!
|
||||
def double_numbers(iterable):
|
||||
double_arr = []
|
||||
for i in iterable:
|
||||
double_arr.append(i + i)
|
||||
return double_arr
|
||||
|
||||
|
||||
# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk
|
||||
# ezt a nagy listát a ciklus vezérléséhez.
|
||||
for value in double_numbers(range(1000000)): # `test_non_generator`
|
||||
print value
|
||||
if value > 5:
|
||||
break
|
||||
|
||||
|
||||
# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet,
|
||||
# amikor azt kérik tőle
|
||||
def double_numbers_generator(iterable):
|
||||
for i in iterable:
|
||||
yield i + i
|
||||
|
||||
|
||||
# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt.
|
||||
# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak
|
||||
# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!).
|
||||
for value in double_numbers_generator(xrange(1000000)): # `test_generator`
|
||||
print value
|
||||
if value > 5:
|
||||
break
|
||||
|
||||
# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén
|
||||
# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a
|
||||
# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range`
|
||||
# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük
|
||||
# - esetünkben a ciklus következő iterációjakor
|
||||
|
||||
# A lista képzéshez hasonlóan generátor képzőket is használhatunk
|
||||
# ("generator comprehensions").
|
||||
values = (-x for x in [1, 2, 3, 4, 5])
|
||||
for x in values:
|
||||
print(x) # kimenet: -1 -2 -3 -4 -5
|
||||
|
||||
# Egy generátor összes generált elemét listaként is elkérhetjük:
|
||||
values = (-x for x in [1, 2, 3, 4, 5])
|
||||
gen_to_list = list(values)
|
||||
print(gen_to_list) # => [-1, -2, -3, -4, -5]
|
||||
|
||||
# Dekorátorok
|
||||
# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény.
|
||||
# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény
|
||||
# kimenetébe beszúrja az 'Apple' elemet.
|
||||
def add_apples(func):
|
||||
def get_fruits():
|
||||
fruits = func()
|
||||
fruits.append('Apple')
|
||||
return fruits
|
||||
return get_fruits
|
||||
|
||||
@add_apples
|
||||
def get_fruits():
|
||||
return ['Banana', 'Mango', 'Orange']
|
||||
|
||||
# A kimenet tartalmazza az 'Apple' elemet:
|
||||
# Banana, Mango, Orange, Apple
|
||||
print ', '.join(get_fruits())
|
||||
|
||||
# Ebben a példában a beg dekorátorral látjuk el a say függvényt.
|
||||
# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor
|
||||
# megváltoztatja az eredmény mondatot.
|
||||
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, "Please! I am poor :(")
|
||||
return msg
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
@beg
|
||||
def say(say_please=False):
|
||||
msg = "Can you buy me a beer?"
|
||||
return msg, say_please
|
||||
|
||||
|
||||
print say() # Can you buy me a beer?
|
||||
print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
|
||||
```
|
||||
|
||||
## Még több érdekel?
|
||||
|
||||
### Ingyenes online tartalmak
|
||||
|
||||
* [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/)
|
||||
* [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/)
|
||||
* [LearnPython](http://www.learnpython.org/)
|
||||
* [Fullstack Python](https://www.fullstackpython.com/)
|
||||
|
||||
### Könyvek
|
||||
|
||||
* [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)
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
language: "Brainfuck"
|
||||
language: bf
|
||||
filename: brainfuck-id.bf
|
||||
contributors:
|
||||
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
|
||||
|
@ -13,7 +13,7 @@ Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax
|
||||
Beri masukan sebanyak-banyaknya! / Jangan sungkan untuk melakukan fork dan pull request!
|
||||
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<!-- Markdown adalah superset dari HTML, jadi setiap berkas HTML adalah markdown yang
|
||||
valid, ini berarti kita dapat menggunakan elemen HTML dalam markdown, seperti elemen
|
||||
komentar, dan ia tidak akan terpengaruh parser markdown. Namun, jika Anda membuat
|
||||
|
135
it-it/asciidoc-it.html.markdown
Normal file
135
it-it/asciidoc-it.html.markdown
Normal file
@ -0,0 +1,135 @@
|
||||
---
|
||||
language: asciidoc
|
||||
contributors:
|
||||
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
|
||||
- ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
|
||||
translators:
|
||||
- ["Ale46", "https://github.com/ale46"]
|
||||
lang: it-it
|
||||
filename: asciidoc-it.md
|
||||
---
|
||||
|
||||
AsciiDoc è un linguaggio di markup simile a Markdown e può essere usato per qualsiasi cosa, dai libri ai blog. Creato nel 2002 da Stuart Rackman, questo linguaggio è semplice ma permette un buon numero di personalizzazioni.
|
||||
|
||||
Intestazione Documento
|
||||
|
||||
Le intestazioni sono opzionali e possono contenere linee vuote. Deve avere almeno una linea vuota rispetto al contenuto.
|
||||
|
||||
Solo titolo
|
||||
|
||||
```
|
||||
= Titolo documento
|
||||
|
||||
Prima frase del documento.
|
||||
```
|
||||
|
||||
Titolo ed Autore
|
||||
|
||||
```
|
||||
= Titolo documento
|
||||
Primo Ultimo <first.last@learnxinyminutes.com>
|
||||
|
||||
Inizio del documento
|
||||
```
|
||||
|
||||
Autori multipli
|
||||
|
||||
```
|
||||
= Titolo Documento
|
||||
John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
|
||||
|
||||
Inizio di un documento con autori multipli.
|
||||
```
|
||||
|
||||
Linea di revisione (richiede una linea autore)
|
||||
|
||||
```
|
||||
= Titolo documento V1
|
||||
Potato Man <chip@crunchy.com>
|
||||
v1.0, 2016-01-13
|
||||
|
||||
Questo articolo sulle patatine sarà divertente.
|
||||
```
|
||||
|
||||
Paragrafi
|
||||
|
||||
```
|
||||
Non hai bisogno di nulla di speciale per i paragrafi.
|
||||
|
||||
Aggiungi una riga vuota tra i paragrafi per separarli.
|
||||
|
||||
Per creare una riga vuota aggiungi un +
|
||||
e riceverai una interruzione di linea!
|
||||
```
|
||||
|
||||
Formattazione Testo
|
||||
|
||||
```
|
||||
_underscore crea corsivo_
|
||||
*asterischi per il grassetto*
|
||||
*_combinali per maggiore divertimento_*
|
||||
`usa i ticks per indicare il monospazio`
|
||||
`*spaziatura fissa in grassetto*`
|
||||
```
|
||||
|
||||
Titoli di sezione
|
||||
|
||||
```
|
||||
= Livello 0 (può essere utilizzato solo nell'intestazione del documento)
|
||||
|
||||
== Livello 1 <h2>
|
||||
|
||||
=== Livello 2 <h3>
|
||||
|
||||
==== Livello 3 <h4>
|
||||
|
||||
===== Livello 4 <h5>
|
||||
|
||||
```
|
||||
|
||||
Liste
|
||||
|
||||
Per creare un elenco puntato, utilizzare gli asterischi.
|
||||
|
||||
```
|
||||
* foo
|
||||
* bar
|
||||
* baz
|
||||
```
|
||||
|
||||
Per creare un elenco numerato usa i periodi.
|
||||
|
||||
```
|
||||
. item 1
|
||||
. item 2
|
||||
. item 3
|
||||
```
|
||||
|
||||
È possibile nidificare elenchi aggiungendo asterischi o periodi aggiuntivi fino a cinque volte.
|
||||
|
||||
```
|
||||
* foo 1
|
||||
** foo 2
|
||||
*** foo 3
|
||||
**** foo 4
|
||||
***** foo 5
|
||||
|
||||
. foo 1
|
||||
.. foo 2
|
||||
... foo 3
|
||||
.... foo 4
|
||||
..... foo 5
|
||||
```
|
||||
|
||||
## Ulteriori letture
|
||||
|
||||
Esistono due strumenti per elaborare i documenti AsciiDoc:
|
||||
|
||||
1. [AsciiDoc](http://asciidoc.org/): implementazione Python originale, disponibile nelle principali distribuzioni Linux. Stabile e attualmente in modalità di manutenzione.
|
||||
2. [Asciidoctor](http://asciidoctor.org/): implementazione alternativa di Ruby, utilizzabile anche da Java e JavaScript. In fase di sviluppo attivo, mira ad estendere la sintassi AsciiDoc con nuove funzionalità e formati di output.
|
||||
|
||||
I seguenti collegamenti sono relativi all'implementazione di `Asciidoctor`:
|
||||
|
||||
* [Markdown - AsciiDoc comparazione sintassi](http://asciidoctor.org/docs/user-manual/#comparison-by-example): confronto affiancato di elementi di Markdown e AsciiDoc comuni.
|
||||
* [Per iniziare](http://asciidoctor.org/docs/#get-started-with-asciidoctor): installazione e guide rapide per il rendering di documenti semplici.
|
||||
* [Asciidoctor Manuale Utente](http://asciidoctor.org/docs/user-manual/): manuale completo con riferimento alla sintassi, esempi, strumenti di rendering, tra gli altri.
|
@ -1130,7 +1130,6 @@ compl 4 // Effettua il NOT bit-a-bit
|
||||
```
|
||||
Letture consigliate:
|
||||
|
||||
Un riferimento aggiornato del linguaggio può essere trovato qui
|
||||
<http://cppreference.com/w/cpp>
|
||||
|
||||
Risorse addizionali possono essere trovate qui <http://cplusplus.com>
|
||||
* Un riferimento aggiornato del linguaggio può essere trovato qui [CPP Reference](http://cppreference.com/w/cpp).
|
||||
* Risorse addizionali possono essere trovate qui [CPlusPlus](http://cplusplus.com).
|
||||
* Un tutorial che copre le basi del linguaggio e l'impostazione dell'ambiente di codifica è disponibile su [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb).
|
||||
|
55
it-it/dynamic-programming-it.html.markdown
Normal file
55
it-it/dynamic-programming-it.html.markdown
Normal file
@ -0,0 +1,55 @@
|
||||
---
|
||||
category: Algorithms & Data Structures
|
||||
name: Dynamic Programming
|
||||
contributors:
|
||||
- ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
|
||||
translators:
|
||||
- ["Ale46", "https://github.com/ale46"]
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
# Programmazione dinamica
|
||||
|
||||
## Introduzione
|
||||
|
||||
La programmazione dinamica è una tecnica potente utilizzata per risolvere una particolare classe di problemi, come vedremo. L'idea è molto semplice, se hai risolto un problema con l'input dato, salva il risultato come riferimento futuro, in modo da evitare di risolvere nuovamente lo stesso problema.
|
||||
|
||||
Ricordate sempre!
|
||||
"Chi non ricorda il passato è condannato a ripeterlo"
|
||||
|
||||
## Modi per risolvere questi problemi
|
||||
|
||||
1. *Top-Down* : Inizia a risolvere il problema specifico suddividendolo. Se vedi che il problema è già stato risolto, rispondi semplicemente con la risposta già salvata. Se non è stato risolto, risolvilo e salva la risposta. Di solito è facile da pensare e molto intuitivo. Questo è indicato come Memoization.
|
||||
|
||||
2. *Bottom-Up* : Analizza il problema e vedi l'ordine in cui i sotto-problemi sono risolti e inizia a risolvere dal sottoproblema banale, verso il problema dato. In questo processo, è garantito che i sottoproblemi vengono risolti prima di risolvere il problema. Si parla di programmazione dinamica.
|
||||
|
||||
## Esempio di programmazione dinamica
|
||||
|
||||
Il problema di "Longest Increasing Subsequence" consiste nel trovare la sottosequenza crescente più lunga di una determinata sequenza. Data una sequenza `S= {a1 , a2 , a3, a4, ............., an-1, an }` dobbiamo trovare il sottoinsieme più lungo tale che per tutti gli `j` e gli `i`, `j<i` nel sotto-insieme `aj<ai`.
|
||||
Prima di tutto dobbiamo trovare il valore delle sottosequenze più lunghe (LSi) ad ogni indice i con l'ultimo elemento della sequenza che è ai. Quindi il più grande LSi sarebbe la sottosequenza più lunga nella sequenza data. Per iniziare LSi viene inizializzato ad 1, dato che ai è un element della sequenza (Ultimo elemento). Quindi per tutti gli `j` tale che `j<i` e `aj<ai`, troviamo il più grande LSj e lo aggiungiamo a LSi. Quindi l'algoritmo richiede un tempo di *O(n2)*.
|
||||
|
||||
Pseudo-codice per trovare la lunghezza della sottosequenza crescente più lunga:
|
||||
Questa complessità degli algoritmi potrebbe essere ridotta usando una migliore struttura dei dati piuttosto che una matrice. La memorizzazione dell'array predecessore e della variabile come `largest_sequences_so_far` e il suo indice farebbero risparmiare molto tempo.
|
||||
|
||||
Un concetto simile potrebbe essere applicato nel trovare il percorso più lungo nel grafico aciclico diretto.
|
||||
|
||||
```python
|
||||
for i=0 to n-1
|
||||
LS[i]=1
|
||||
for j=0 to i-1
|
||||
if (a[i] > a[j] and LS[i]<LS[j])
|
||||
LS[i] = LS[j]+1
|
||||
for i=0 to n-1
|
||||
if (largest < LS[i])
|
||||
```
|
||||
|
||||
### Alcuni famosi problemi DP
|
||||
|
||||
- Floyd Warshall Algorithm - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]()
|
||||
- Integer Knapsack Problem - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]()
|
||||
- Longest Common Subsequence - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]()
|
||||
|
||||
|
||||
## Risorse online
|
||||
|
||||
* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming)
|
@ -270,12 +270,13 @@ func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string {
|
||||
}
|
||||
|
||||
func imparaDefer() (ok bool) {
|
||||
// Le istruzioni dette "deferred" (rinviate) sono eseguite
|
||||
// appena prima che la funzione abbia termine.
|
||||
// La parola chiave "defer" inserisce una funzione in una lista.
|
||||
// La lista contenente tutte le chiamate a funzione viene eseguita DOPO
|
||||
// il return finale della funzione che le circonda.
|
||||
defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).")
|
||||
defer fmt.Println("\nQuesta riga viene stampata per prima perché")
|
||||
// defer viene usato di solito per chiudere un file, così la funzione che
|
||||
// chiude il file viene messa vicino a quella che lo apre.
|
||||
// chiude il file, preceduta da "defer", viene messa vicino a quella che lo apre.
|
||||
return true
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
language: html
|
||||
filename: learnhtml-it.html
|
||||
filename: learnhtml-it.txt
|
||||
contributors:
|
||||
- ["Christophe THOMAS", "https://github.com/WinChris"]
|
||||
translators:
|
||||
@ -112,7 +112,7 @@ Questo articolo riguarda principalmente la sintassi HTML ed alcuni suggerimenti
|
||||
|
||||
## Uso
|
||||
|
||||
HTML è scritto in files che finiscono con `.html`.
|
||||
HTML è scritto in files che finiscono con `.html` o `.htm`. Il "MIME type" è `text/html`.
|
||||
|
||||
## Per saperne di più
|
||||
|
||||
|
@ -17,14 +17,14 @@ concorrente, basato su classi e adatto a svariati scopi.
|
||||
```java
|
||||
// I commenti su singola linea incominciano con //
|
||||
/*
|
||||
I commenti su piu' linee invece sono cosi'
|
||||
I commenti su più linee invece sono così
|
||||
*/
|
||||
/**
|
||||
I commenti per la documentazione JavaDoc si fanno cosi'.
|
||||
I commenti per la documentazione JavaDoc si fanno così.
|
||||
Vengono usati per descrivere una classe o alcuni suoi attributi.
|
||||
*/
|
||||
|
||||
// Per importare la classe ArrayList conenuta nel package java.util
|
||||
// Per importare la classe ArrayList contenuta nel package java.util
|
||||
import java.util.ArrayList;
|
||||
// Per importare tutte le classi contenute nel package java.security
|
||||
import java.security.*;
|
||||
@ -48,7 +48,7 @@ public class LearnJava {
|
||||
System.out.print("Ciao ");
|
||||
System.out.print("Mondo ");
|
||||
|
||||
// Per stampare del testo formattato, si puo' usare System.out.printf
|
||||
// Per stampare del testo formattato, si può usare System.out.printf
|
||||
System.out.printf("pi greco = %.5f", Math.PI); // => pi greco = 3.14159
|
||||
|
||||
///////////////////////////////////////
|
||||
@ -60,7 +60,7 @@ public class LearnJava {
|
||||
*/
|
||||
// Per dichiarare una variabile basta fare <tipoDato> <nomeVariabile>
|
||||
int fooInt;
|
||||
// Per dichiarare piu' di una variabile dello lo stesso tipo si usa:
|
||||
// Per dichiarare più di una variabile dello lo stesso tipo si usa:
|
||||
// <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3>
|
||||
int fooInt1, fooInt2, fooInt3;
|
||||
|
||||
@ -71,7 +71,7 @@ public class LearnJava {
|
||||
// Per inizializzare una variabile si usa
|
||||
// <tipoDato> <nomeVariabile> = <valore>
|
||||
int fooInt = 1;
|
||||
// Per inizializzare piu' di una variabile dello lo stesso tipo
|
||||
// Per inizializzare più di una variabile dello lo stesso tipo
|
||||
// si usa <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> = <valore>
|
||||
int fooInt1, fooInt2, fooInt3;
|
||||
fooInt1 = fooInt2 = fooInt3 = 1;
|
||||
@ -94,7 +94,7 @@ public class LearnJava {
|
||||
// Long - intero con segno a 64 bit (in complemento a 2)
|
||||
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
|
||||
long fooLong = 100000L;
|
||||
// L viene usato per indicare che il valore e' di tipo Long;
|
||||
// L viene usato per indicare che il valore è di tipo Long;
|
||||
// altrimenti il valore viene considerato come intero.
|
||||
|
||||
// Nota: Java non dispone di interi senza segno.
|
||||
@ -102,14 +102,14 @@ public class LearnJava {
|
||||
// Float - Numero in virgola mobile a 32 bit con precisione singola (IEEE 754)
|
||||
// 2^-149 <= float <= (2-2^-23) * 2^127
|
||||
float fooFloat = 234.5f;
|
||||
// f o F indicano the la variabile e' di tipo float;
|
||||
// f o F indicano the la variabile è di tipo float;
|
||||
// altrimenti il valore viene considerato come double.
|
||||
|
||||
// Double - Numero in virgola mobile a 64 bit con precisione doppia (IEEE 754)
|
||||
// 2^-1074 <= x <= (2-2^-52) * 2^1023
|
||||
double fooDouble = 123.4;
|
||||
|
||||
// Boolean - Puo' assumere il valore vero (true) o falso (false)
|
||||
// Boolean - Può assumere il valore vero (true) o falso (false)
|
||||
boolean fooBoolean = true;
|
||||
boolean barBoolean = false;
|
||||
|
||||
@ -118,26 +118,26 @@ public class LearnJava {
|
||||
|
||||
// Le variabili precedute da final possono essere inizializzate una volta sola,
|
||||
final int HOURS_I_WORK_PER_WEEK = 9001;
|
||||
// pero' e' possibile dichiararle e poi inizializzarle in un secondo momento.
|
||||
// però è possibile dichiararle e poi inizializzarle in un secondo momento.
|
||||
final double E;
|
||||
E = 2.71828;
|
||||
|
||||
|
||||
// BigInteger - Interi a precisione arbitraria
|
||||
//
|
||||
// BigInteger e' un tipo di dato che permette ai programmatori di
|
||||
// gestire interi piu' grandi di 64 bit. Internamente, le variabili
|
||||
// BigInteger è un tipo di dato che permette ai programmatori di
|
||||
// gestire interi più grandi di 64 bit. Internamente, le variabili
|
||||
// di tipo BigInteger vengono memorizzate come un vettore di byte e
|
||||
// vengono manipolate usando funzioni dentro la classe BigInteger.
|
||||
//
|
||||
// Una variabile di tipo BigInteger puo' essere inizializzata usando
|
||||
// Una variabile di tipo BigInteger può essere inizializzata usando
|
||||
// un array di byte oppure una stringa.
|
||||
|
||||
BigInteger fooBigInteger = new BigDecimal(fooByteArray);
|
||||
|
||||
// BigDecimal - Numero con segno, immutabile, a precisione arbitraria
|
||||
//
|
||||
// Una variabile di tipo BigDecimal e' composta da due parti: un intero
|
||||
// Una variabile di tipo BigDecimal è composta da due parti: un intero
|
||||
// a precisione arbitraria detto 'non scalato', e un intero a 32 bit
|
||||
// che rappresenta la 'scala', ovvero la potenza di 10 con cui
|
||||
// moltiplicare l'intero non scalato.
|
||||
@ -158,9 +158,9 @@ public class LearnJava {
|
||||
// Stringhe
|
||||
String fooString = "Questa e' la mia stringa!";
|
||||
|
||||
// \n e' un carattere di escape che rappresenta l'andare a capo
|
||||
// \n è un carattere di escape che rappresenta l'andare a capo
|
||||
String barString = "Stampare su una nuova riga?\nNessun problema!";
|
||||
// \t e' un carattere di escape che aggiunge un tab
|
||||
// \t è un carattere di escape che aggiunge un tab
|
||||
String bazString = "Vuoi aggiungere un tab?\tNessun problema!";
|
||||
System.out.println(fooString);
|
||||
System.out.println(barString);
|
||||
@ -168,7 +168,7 @@ public class LearnJava {
|
||||
|
||||
// Vettori
|
||||
// La dimensione di un array deve essere decisa in fase di
|
||||
// istanziazione. Per dichiarare un array si puo' fare in due modi:
|
||||
// istanziazione. Per dichiarare un array si può fare in due modi:
|
||||
// <tipoDato>[] <nomeVariabile> = new <tipoDato>[<dimensioneArray>];
|
||||
// <tipoDato> <nomeVariabile>[] = new <tipoDato>[<dimensioneArray>];
|
||||
int[] intArray = new int[10];
|
||||
@ -189,8 +189,8 @@ public class LearnJava {
|
||||
System.out.println("intArray @ 1: " + intArray[1]); // => 1
|
||||
|
||||
// Ci sono altri tipo di dato interessanti.
|
||||
// ArrayList - Simili ai vettori, pero' offrono altre funzionalita',
|
||||
// e la loro dimensione puo' essere modificata.
|
||||
// ArrayList - Simili ai vettori, però offrono altre funzionalità,
|
||||
// e la loro dimensione può essere modificata.
|
||||
// LinkedList - Si tratta di una lista linkata doppia, e come tale
|
||||
// implementa tutte le operazioni del caso.
|
||||
// Map - Un insieme di oggetti che fa corrispondere delle chiavi
|
||||
@ -207,7 +207,7 @@ public class LearnJava {
|
||||
|
||||
int i1 = 1, i2 = 2; // Dichiarazone multipla in contemporanea
|
||||
|
||||
// L'aritmetica e' lineare.
|
||||
// L'aritmetica è lineare.
|
||||
System.out.println("1+2 = " + (i1 + i2)); // => 3
|
||||
System.out.println("2-1 = " + (i2 - i1)); // => 1
|
||||
System.out.println("2*1 = " + (i2 * i1)); // => 2
|
||||
@ -253,7 +253,7 @@ public class LearnJava {
|
||||
///////////////////////////////////////
|
||||
System.out.println("\n->Strutture di controllo");
|
||||
|
||||
// La dichiarazione dell'If e'' C-like.
|
||||
// La dichiarazione dell'If è C-like.
|
||||
int j = 10;
|
||||
if (j == 10){
|
||||
System.out.println("Io vengo stampato");
|
||||
@ -328,18 +328,18 @@ public class LearnJava {
|
||||
System.out.println("Risultato del costrutto switch: " + stringaMese);
|
||||
|
||||
// Condizioni brevi
|
||||
// Si puo' usare l'operatore '?' per un rapido assegnamento
|
||||
// Si può usare l'operatore '?' per un rapido assegnamento
|
||||
// o per operazioni logiche.
|
||||
// Si legge:
|
||||
// Se (condizione) e' vera, usa <primo valore>, altrimenti usa <secondo valore>
|
||||
// Se (condizione) è vera, usa <primo valore>, altrimenti usa <secondo valore>
|
||||
int foo = 5;
|
||||
String bar = (foo < 10) ? "A" : "B";
|
||||
System.out.println("Se la condizione e' vera stampa A: "+bar);
|
||||
// Stampa A, perche' la condizione e' vera.
|
||||
// Stampa A, perché la condizione è vera.
|
||||
|
||||
|
||||
/////////////////////////////////////////
|
||||
// Convertire i tipi di tati e Typcasting
|
||||
// Convertire i tipi di dati e Typecasting
|
||||
/////////////////////////////////////////
|
||||
|
||||
// Convertire tipi di dati
|
||||
@ -397,16 +397,16 @@ class Bicicletta {
|
||||
|
||||
// Variabili della bicicletta
|
||||
public int cadenza;
|
||||
// Public: Puo' essere richiamato da qualsiasi classe
|
||||
// Public: Può essere richiamato da qualsiasi classe
|
||||
private int velocita;
|
||||
// Private: e'' accessibile solo dalla classe dove e'' stato inizializzato
|
||||
// Private: è accessibile solo dalla classe dove è stato inizializzato
|
||||
protected int ingranaggi;
|
||||
// Protected: e'' visto sia dalla classe che dalle sottoclassi
|
||||
// Protected: è visto sia dalla classe che dalle sottoclassi
|
||||
String nome;
|
||||
// default: e'' accessibile sono all'interno dello stesso package
|
||||
// default: è accessibile sono all'interno dello stesso package
|
||||
|
||||
// I costruttori vengono usati per creare variabili
|
||||
// Questo e'' un costruttore
|
||||
// Questo è un costruttore
|
||||
public Bicicletta() {
|
||||
ingranaggi = 1;
|
||||
cadenza = 50;
|
||||
@ -414,7 +414,7 @@ class Bicicletta {
|
||||
nome = "Bontrager";
|
||||
}
|
||||
|
||||
// Questo e'' un costruttore che richiede parametri
|
||||
// Questo è un costruttore che richiede parametri
|
||||
public Bicicletta(int cadenza, int velocita, int ingranaggi, String nome) {
|
||||
this.ingranaggi = ingranaggi;
|
||||
this.cadenza = cadenza;
|
||||
@ -469,7 +469,7 @@ class Bicicletta {
|
||||
}
|
||||
} // Fine classe bicicletta
|
||||
|
||||
// PennyFarthing e'' una sottoclasse della bicicletta
|
||||
// PennyFarthing è una sottoclasse della bicicletta
|
||||
class PennyFarthing extends Bicicletta {
|
||||
// (Sono quelle biciclette con un unica ruota enorme
|
||||
// Non hanno ingranaggi.)
|
||||
@ -481,7 +481,7 @@ class PennyFarthing extends Bicicletta {
|
||||
|
||||
// Bisogna contrassegnre un medodo che si sta riscrivendo
|
||||
// con una @annotazione
|
||||
// Per saperne di piu' sulle annotazioni
|
||||
// Per saperne di più sulle annotazioni
|
||||
// Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/
|
||||
@Override
|
||||
public void setIngranaggi(int ingranaggi) {
|
||||
@ -518,8 +518,8 @@ class Frutta implements Commestibile, Digestibile {
|
||||
}
|
||||
}
|
||||
|
||||
//In Java si puo' estendere solo una classe, ma si possono implementare
|
||||
//piu' interfaccie, per esempio:
|
||||
//In Java si può estendere solo una classe, ma si possono implementare
|
||||
//più interfaccie, per esempio:
|
||||
class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia {
|
||||
public void MetodoPrimaInterfaccia() {
|
||||
|
||||
|
131
it-it/jquery-it.html.markdown
Normal file
131
it-it/jquery-it.html.markdown
Normal file
@ -0,0 +1,131 @@
|
||||
---
|
||||
category: tool
|
||||
tool: jquery
|
||||
contributors:
|
||||
- ["Sawyer Charles", "https://github.com/xssc"]
|
||||
filename: jquery-it.js
|
||||
translators:
|
||||
- ["Ale46", "https://github.com/ale46"]
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
jQuery è una libreria JavaScript che ti aiuta a "fare di più, scrivendo meno". Rende molte attività comuni di JavaScript più facili da scrivere. jQuery è utilizzato da molte grandi aziende e sviluppatori in tutto il mondo. Rende AJAX, gestione degli eventi, manipolazione dei documenti e molto altro, più facile e veloce.
|
||||
|
||||
Visto che jQuery è una libreria JavaScript dovresti prima [imparare JavaScript](https://learnxinyminutes.com/docs/javascript/)
|
||||
|
||||
```js
|
||||
|
||||
|
||||
///////////////////////////////////
|
||||
// 1. Selettori
|
||||
|
||||
// I selettori in jQuery vengono utilizzati per selezionare un elemento
|
||||
var page = $(window); // Seleziona l'intera finestra
|
||||
|
||||
// I selettori possono anche essere selettori CSS
|
||||
var paragraph = $('p'); // Seleziona tutti gli elementi del paragrafo
|
||||
var table1 = $('#table1'); // Seleziona elemento con id 'table1'
|
||||
var squares = $('.square'); // Seleziona tutti gli elementi con la classe 'square'
|
||||
var square_p = $('p.square') // Seleziona i paragrafi con la classe 'square'
|
||||
|
||||
|
||||
///////////////////////////////////
|
||||
// 2. Eventi ed effetti
|
||||
// jQuery è molto bravo a gestire ciò che accade quando un evento viene attivato
|
||||
// Un evento molto comune è l'evento "pronto" sul documento
|
||||
// Puoi usare il metodo 'ready' per aspettare che l'elemento abbia finito di caricare
|
||||
$(document).ready(function(){
|
||||
// Il codice non verrà eseguito fino a quando il documento non verrà caricato
|
||||
});
|
||||
// Puoi anche usare funzioni definite
|
||||
function onAction() {
|
||||
// Questo viene eseguito quando l'evento viene attivato
|
||||
}
|
||||
$('#btn').click(onAction); // Invoca onAction al click
|
||||
|
||||
// Alcuni altri eventi comuni sono:
|
||||
$('#btn').dblclick(onAction); // Doppio click
|
||||
$('#btn').hover(onAction); // Al passaggio del mouse
|
||||
$('#btn').focus(onAction); // Al focus
|
||||
$('#btn').blur(onAction); // Focus perso
|
||||
$('#btn').submit(onAction); // Al submit
|
||||
$('#btn').select(onAction); // Quando un elemento è selezionato
|
||||
$('#btn').keydown(onAction); // Quando un tasto è premuto (ma non rilasciato)
|
||||
$('#btn').keyup(onAction); // Quando viene rilasciato un tasto
|
||||
$('#btn').keypress(onAction); // Quando viene premuto un tasto
|
||||
$('#btn').mousemove(onAction); // Quando il mouse viene spostato
|
||||
$('#btn').mouseenter(onAction); // Il mouse entra nell'elemento
|
||||
$('#btn').mouseleave(onAction); // Il mouse lascia l'elemento
|
||||
|
||||
|
||||
// Questi possono anche innescare l'evento invece di gestirlo
|
||||
// semplicemente non passando alcun parametro
|
||||
$('#btn').dblclick(); // Innesca il doppio click sull'elemento
|
||||
|
||||
// Puoi gestire più eventi mentre usi il selettore solo una volta
|
||||
$('#btn').on(
|
||||
{dblclick: myFunction1} // Attivato con doppio clic
|
||||
{blur: myFunction1} // Attivato al blur
|
||||
);
|
||||
|
||||
// Puoi spostare e nascondere elementi con alcuni metodi di effetto
|
||||
$('.table').hide(); // Nascondi gli elementi
|
||||
|
||||
// Nota: chiamare una funzione in questi metodi nasconderà comunque l'elemento
|
||||
$('.table').hide(function(){
|
||||
// Elemento nascosto quindi funzione eseguita
|
||||
});
|
||||
|
||||
// È possibile memorizzare selettori in variabili
|
||||
var tables = $('.table');
|
||||
|
||||
// Alcuni metodi di manipolazione dei documenti di base sono:
|
||||
tables.hide(); // Nascondi elementi
|
||||
tables.show(); // Mostra elementi
|
||||
tables.toggle(); // Cambia lo stato nascondi/mostra
|
||||
tables.fadeOut(); // Fades out
|
||||
tables.fadeIn(); // Fades in
|
||||
tables.fadeToggle(); // Fades in o out
|
||||
tables.fadeTo(0.5); // Dissolve in opacità (tra 0 e 1)
|
||||
tables.slideUp(); // Scorre verso l'alto
|
||||
tables.slideDown(); // Scorre verso il basso
|
||||
tables.slideToggle(); // Scorre su o giù
|
||||
|
||||
// Tutti i precedenti prendono una velocità (millisecondi) e la funzione di callback
|
||||
tables.hide(1000, myFunction); // nasconde l'animazione per 1 secondo quindi esegue la funzione
|
||||
|
||||
// fadeTo ha un'opacità richiesta come secondo parametro
|
||||
tables.fadeTo(2000, 0.1, myFunction); // esegue in 2 sec. il fade sino ad una opacità di 0.1 opacity e poi la funzione
|
||||
|
||||
// Puoi ottenere un effetti più avanzati con il metodo animate
|
||||
tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
|
||||
// Il metodo animate accetta un oggetto di css e valori con cui terminare,
|
||||
// parametri opzionali per affinare l'animazione,
|
||||
// e naturalmente la funzione di callback
|
||||
|
||||
///////////////////////////////////
|
||||
// 3. Manipolazione
|
||||
|
||||
// Questi sono simili agli effetti ma possono fare di più
|
||||
$('div').addClass('taming-slim-20'); // Aggiunge la classe taming-slim-20 a tutti i div
|
||||
|
||||
// Metodi di manipolazione comuni
|
||||
$('p').append('Hello world'); // Aggiunge alla fine dell'elemento
|
||||
$('p').attr('class'); // Ottiene l'attributo
|
||||
$('p').attr('class', 'content'); // Imposta l'attributo
|
||||
$('p').hasClass('taming-slim-20'); // Restituisce vero se ha la classe
|
||||
$('p').height(); // Ottiene l'altezza dell'elemento o imposta l'altezza
|
||||
|
||||
|
||||
// Per molti metodi di manipolazione, ottenere informazioni su un elemento
|
||||
// restituirà SOLO il primo elemento corrispondente
|
||||
$('p').height(); // Ottiene solo la prima altezza del tag 'p'
|
||||
|
||||
// È possibile utilizzare each per scorrere tutti gli elementi
|
||||
var heights = [];
|
||||
$('p').each(function() {
|
||||
heights.push($(this).height()); // Aggiunge tutte le altezze del tag 'p' all'array
|
||||
});
|
||||
|
||||
|
||||
```
|
@ -28,7 +28,7 @@ Markdown varia nelle sue implementazioni da un parser all'altro. Questa guida ce
|
||||
## Elementi HTML
|
||||
Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<!-- Questo significa che possiamo usare elementi di HTML in Markdown, come per esempio i commenti,
|
||||
e questi non saranno modificati dal parser di Markdown. State attenti però,
|
||||
se inserite un elemento HTML nel vostro file Markdown, non potrete usare la sua sintassi
|
||||
@ -39,7 +39,7 @@ all'interno del contenuto dell'elemento. -->
|
||||
|
||||
Potete creare gli elementi HTML da `<h1>` a `<h6>` facilmente, basta che inseriate un egual numero di caratteri cancelletto (#) prima del testo che volete all'interno dell'elemento
|
||||
|
||||
```markdown
|
||||
```md
|
||||
# Questo è un <h1>
|
||||
## Questo è un <h2>
|
||||
### Questo è un <h3>
|
||||
@ -49,7 +49,7 @@ Potete creare gli elementi HTML da `<h1>` a `<h6>` facilmente, basta che inseria
|
||||
```
|
||||
Markdown inoltre fornisce due alternative per indicare gli elementi h1 e h2
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Questo è un h1
|
||||
==============
|
||||
|
||||
@ -60,7 +60,7 @@ Questo è un h2
|
||||
## Stili di testo semplici
|
||||
Il testo può essere stilizzato in corsivo o grassetto usando markdown
|
||||
|
||||
```markdown
|
||||
```md
|
||||
*Questo testo è in corsivo.*
|
||||
_Come pure questo._
|
||||
|
||||
@ -74,12 +74,12 @@ __Come pure questo.__
|
||||
|
||||
In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su Github, è presente anche lo stile barrato:
|
||||
|
||||
```markdown
|
||||
```md
|
||||
~~Questo testo è barrato.~~
|
||||
```
|
||||
## Paragrafi
|
||||
|
||||
```markdown
|
||||
```md
|
||||
I paragrafi sono una o più linee di testo adiacenti separate da una o più righe vuote.
|
||||
|
||||
Questo è un paragrafo. Sto scrivendo in un paragrafo, non è divertente?
|
||||
@ -93,7 +93,7 @@ Qui siamo nel paragrafo 3!
|
||||
|
||||
Se volete inserire l'elemento HTML `<br />`, potete terminare la linea con due o più spazi e poi iniziare un nuovo paragrafo.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Questa frase finisce con due spazi (evidenziatemi per vederli).
|
||||
|
||||
C'è un <br /> sopra di me!
|
||||
@ -101,7 +101,7 @@ C'è un <br /> sopra di me!
|
||||
|
||||
Le citazioni sono semplici da inserire, basta usare il carattere >.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
> Questa è una citazione. Potete
|
||||
> mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente.
|
||||
> Non c'è alcuna differenza, basta che iniziate ogni riga con `>`.
|
||||
@ -115,7 +115,7 @@ Le citazioni sono semplici da inserire, basta usare il carattere >.
|
||||
## Liste
|
||||
Le liste non ordinate possono essere inserite usando gli asterischi, il simbolo più o dei trattini
|
||||
|
||||
```markdown
|
||||
```md
|
||||
* Oggetto
|
||||
* Oggetto
|
||||
* Altro oggetto
|
||||
@ -135,7 +135,7 @@ oppure
|
||||
|
||||
Le liste ordinate invece, sono inserite con un numero seguito da un punto.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. Primo oggetto
|
||||
2. Secondo oggetto
|
||||
3. Terzo oggetto
|
||||
@ -143,7 +143,7 @@ Le liste ordinate invece, sono inserite con un numero seguito da un punto.
|
||||
|
||||
Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzerà comunque nell'ordine corretto, anche se potrebbe non essere una buona idea.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. Primo oggetto
|
||||
1. Secondo oggetto
|
||||
1. Terzo oggetto
|
||||
@ -152,7 +152,7 @@ Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzer
|
||||
|
||||
Potete inserire anche sotto liste
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. Primo oggetto
|
||||
2. Secondo oggetto
|
||||
3. Terzo oggetto
|
||||
@ -163,7 +163,7 @@ Potete inserire anche sotto liste
|
||||
|
||||
Sono presenti anche le task list. In questo modo è possibile creare checkbox in HTML.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
I box senza la 'x' sono checkbox HTML ancora da completare.
|
||||
- [ ] Primo task da completare.
|
||||
- [ ] Secondo task che deve essere completato.
|
||||
@ -174,14 +174,14 @@ Il box subito sotto è una checkbox HTML spuntata.
|
||||
|
||||
Potete inserire un estratto di codice (che utilizza l'elemento `<code>`) indentando una linea con quattro spazi oppure con un carattere tab.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Questa è una linea di codice
|
||||
Come questa
|
||||
```
|
||||
|
||||
Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vostro codice
|
||||
|
||||
```markdown
|
||||
```md
|
||||
my_array.each do |item|
|
||||
puts item
|
||||
end
|
||||
@ -189,7 +189,7 @@ Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vo
|
||||
|
||||
Codice inline può essere inserito usando il carattere backtick `
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`!
|
||||
```
|
||||
|
||||
@ -205,7 +205,7 @@ Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre
|
||||
## Linea orizzontale
|
||||
Le linee orizzontali (`<hr/>`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
***
|
||||
---
|
||||
- - -
|
||||
@ -215,24 +215,24 @@ Le linee orizzontali (`<hr/>`) sono inserite facilmente usanto tre o più asteri
|
||||
## Links
|
||||
Una delle funzionalità migliori di markdown è la facilità con cui si possono inserire i link. Mettete il testo da visualizzare fra parentesi quadre [] seguite dall'url messo fra parentesi tonde ()
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[Cliccami!](http://test.com/)
|
||||
```
|
||||
|
||||
Potete inoltre aggiungere al link un titolo mettendolo fra doppi apici dopo il link
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[Cliccami!](http://test.com/ "Link a Test.com")
|
||||
```
|
||||
|
||||
La sintassi funziona anche con i path relativi.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[Vai a musica](/music/).
|
||||
```
|
||||
|
||||
Markdown supporta inoltre anche la possibilità di aggiungere i link facendo riferimento ad altri punti del testo.
|
||||
```markdown
|
||||
```md
|
||||
[Apri questo link][link1] per più informazioni!
|
||||
[Guarda anche questo link][foobar] se ti va.
|
||||
|
||||
@ -242,7 +242,7 @@ Markdown supporta inoltre anche la possibilità di aggiungere i link facendo rif
|
||||
l titolo può anche essere inserito in apici singoli o in parentesi, oppure omesso interamente. Il riferimento può essere inserito in un punto qualsiasi del vostro documento e l'identificativo del riferimento può essere lungo a piacere a patto che sia univoco.
|
||||
|
||||
Esiste anche un "identificativo implicito" che vi permette di usare il testo del link come id.
|
||||
```markdown
|
||||
```md
|
||||
[Questo][] è un link.
|
||||
|
||||
[Questo]: http://thisisalink.com/
|
||||
@ -252,13 +252,13 @@ Ma non è comunemente usato.
|
||||
## Immagini
|
||||
Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre!
|
||||
|
||||
```markdown
|
||||
```md
|
||||
![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale")
|
||||
```
|
||||
|
||||
E la modalità a riferimento funziona esattamente come ci si aspetta
|
||||
|
||||
```markdown
|
||||
```md
|
||||
![Questo è il testo alternativo.][myimage]
|
||||
|
||||
[myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui"
|
||||
@ -266,25 +266,25 @@ E la modalità a riferimento funziona esattamente come ci si aspetta
|
||||
## Miscellanea
|
||||
### Auto link
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<http://testwebsite.com/> è equivalente ad
|
||||
[http://testwebsite.com/](http://testwebsite.com/)
|
||||
```
|
||||
### Auto link per le email
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<foo@bar.com>
|
||||
```
|
||||
### Caratteri di escaping
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*.
|
||||
```
|
||||
|
||||
### Combinazioni di tasti
|
||||
In Github Flavored Markdown, potete utilizzare il tag `<kbd>` per raffigurare i tasti della tastiera.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Il tuo computer è crashato? Prova a premere
|
||||
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Canc</kbd>
|
||||
```
|
||||
@ -292,7 +292,7 @@ Il tuo computer è crashato? Prova a premere
|
||||
### Tabelle
|
||||
Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue:
|
||||
|
||||
```markdown
|
||||
```md
|
||||
| Col1 | Col2 | Col3 |
|
||||
| :------------------- | :------: | -----------------: |
|
||||
| Allineato a sinistra | Centrato | Allineato a destra |
|
||||
@ -300,7 +300,7 @@ Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente
|
||||
```
|
||||
oppure, per lo stesso risultato
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Col 1 | Col2 | Col3
|
||||
:-- | :-: | --:
|
||||
È una cosa orrenda | fatela | finire in fretta
|
||||
|
@ -199,8 +199,7 @@ size(A) % ans = 3 3
|
||||
A(1, :) =[] % Rimuove la prima riga della matrice
|
||||
A(:, 1) =[] % Rimuove la prima colonna della matrice
|
||||
|
||||
transpose(A) % Traspone la matrice, equivale a:
|
||||
A one
|
||||
transpose(A) % Traspone la matrice, equivale a: A.'
|
||||
ctranspose(A) % Trasposizione hermitiana della matrice
|
||||
% (ovvero il complesso coniugato di ogni elemento della matrice trasposta)
|
||||
|
||||
|
80
it-it/pcre-it.html.markdown
Normal file
80
it-it/pcre-it.html.markdown
Normal file
@ -0,0 +1,80 @@
|
||||
---
|
||||
language: PCRE
|
||||
filename: pcre-it.txt
|
||||
contributors:
|
||||
- ["Sachin Divekar", "http://github.com/ssd532"]
|
||||
translators:
|
||||
- ["Christian Grasso", "https://grasso.io"]
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
Un'espressione regolare (regex o regexp in breve) è una speciale stringa
|
||||
utilizzata per definire un pattern, ad esempio per cercare una sequenza di
|
||||
caratteri; ad esempio, `/^[a-z]+:/` può essere usato per estrarre `http:`
|
||||
dall'URL `http://github.com/`.
|
||||
|
||||
PCRE (Perl Compatible Regular Expressions) è una libreria per i regex in C.
|
||||
La sintassi utilizzata per le espressioni è molto simile a quella di Perl, da
|
||||
cui il nome. Si tratta di una delle sintassi più diffuse per la scrittura di
|
||||
regex.
|
||||
|
||||
Esistono due tipi di metacaratteri (caratteri con una funzione speciale):
|
||||
* Caratteri riconosciuti ovunque tranne che nelle parentesi quadre
|
||||
```
|
||||
\ carattere di escape
|
||||
^ cerca all'inizio della stringa (o della riga, in modalità multiline)
|
||||
$ cerca alla fine della stringa (o della riga, in modalità multiline)
|
||||
. qualsiasi carattere eccetto le newline
|
||||
[ inizio classe di caratteri
|
||||
| separatore condizioni alternative
|
||||
( inizio subpattern
|
||||
) fine subpattern
|
||||
? quantificatore "0 o 1"
|
||||
* quantificatore "0 o più"
|
||||
+ quantificatore "1 o più"
|
||||
{ inizio quantificatore numerico
|
||||
```
|
||||
|
||||
* Caratteri riconosciuti nelle parentesi quadre
|
||||
```
|
||||
\ carattere di escape
|
||||
^ nega la classe se è il primo carattere
|
||||
- indica una serie di caratteri
|
||||
[ classe caratteri POSIX (se seguita dalla sintassi POSIX)
|
||||
] termina la classe caratteri
|
||||
|
||||
```
|
||||
|
||||
PCRE fornisce inoltre delle classi di caratteri predefinite:
|
||||
```
|
||||
\d cifra decimale
|
||||
\D NON cifra decimale
|
||||
\h spazio vuoto orizzontale
|
||||
\H NON spazio vuoto orizzontale
|
||||
\s spazio
|
||||
\S NON spazio
|
||||
\v spazio vuoto verticale
|
||||
\V NON spazio vuoto verticale
|
||||
\w parola
|
||||
\W "NON parola"
|
||||
```
|
||||
|
||||
## Esempi
|
||||
|
||||
Utilizzeremo la seguente stringa per i nostri test:
|
||||
```
|
||||
66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1"
|
||||
```
|
||||
Si tratta di una riga di log del web server Apache.
|
||||
|
||||
| Regex | Risultato | Commento |
|
||||
| :---- | :-------------- | :------ |
|
||||
| `GET` | GET | Cerca esattamente la stringa "GET" (case sensitive) |
|
||||
| `\d+.\d+.\d+.\d+` | 66.249.64.13 | `\d+` identifica uno o più (quantificatore `+`) numeri [0-9], `\.` identifica il carattere `.` |
|
||||
| `(\d+\.){3}\d+` | 66.249.64.13 | `(\d+\.){3}` cerca il gruppo (`\d+\.`) esattamente 3 volte. |
|
||||
| `\[.+\]` | [18/Sep/2004:11:07:48 +1000] | `.+` identifica qualsiasi carattere, eccetto le newline; `.` indica un carattere qualsiasi |
|
||||
| `^\S+` | 66.249.64.13 | `^` cerca all'inizio della stringa, `\S+` identifica la prima stringa di caratteri diversi dallo spazio |
|
||||
| `\+[0-9]+` | +1000 | `\+` identifica il carattere `+`. `[0-9]` indica una cifra da 0 a 9. L'espressione è equivalente a `\+\d+` |
|
||||
|
||||
## Altre risorse
|
||||
[Regex101](https://regex101.com/) - tester per le espressioni regolari
|
85
it-it/pyqt-it.html.markdown
Normal file
85
it-it/pyqt-it.html.markdown
Normal file
@ -0,0 +1,85 @@
|
||||
---
|
||||
category: tool
|
||||
tool: PyQT
|
||||
filename: learnpyqt.py
|
||||
contributors:
|
||||
- ["Nathan Hughes", "https://github.com/sirsharpest"]
|
||||
translators:
|
||||
- ["Ale46", "https://github.com/ale46"]
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*.
|
||||
|
||||
|
||||
Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192
|
||||
), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità
|
||||
che avrebbero se fossero fatte usando pyqt!
|
||||
|
||||
```python
|
||||
import sys
|
||||
from PyQt4 import QtGui
|
||||
|
||||
def window():
|
||||
# Crea un oggetto applicazione
|
||||
app = QtGui.QApplication(sys.argv)
|
||||
# Crea un widget in cui verrà inserita la nostra etichetta
|
||||
w = QtGui.QWidget()
|
||||
# Aggiungi un'etichetta al widget
|
||||
b = QtGui.QLabel(w)
|
||||
# Imposta del testo per l'etichetta
|
||||
b.setText("Ciao Mondo!")
|
||||
# Fornisce informazioni su dimensioni e posizionamento
|
||||
w.setGeometry(100, 100, 200, 50)
|
||||
b.move(50, 20)
|
||||
# Dai alla nostra finestra un bel titolo
|
||||
w.setWindowTitle("PyQt")
|
||||
# Visualizza tutto
|
||||
w.show()
|
||||
# Esegui ciò che abbiamo chiesto, una volta che tutto è stato configurato
|
||||
sys.exit(app.exec_())
|
||||
|
||||
if __name__ == '__main__':
|
||||
window()
|
||||
|
||||
```
|
||||
|
||||
Per ottenere alcune delle funzionalità più avanzate in **pyqt**, dobbiamo iniziare a cercare di creare elementi aggiuntivi.
|
||||
Qui mostriamo come creare una finestra popup di dialogo, utile per chiedere all'utente di confermare una decisione o fornire informazioni
|
||||
|
||||
```Python
|
||||
import sys
|
||||
from PyQt4.QtGui import *
|
||||
from PyQt4.QtCore import *
|
||||
|
||||
|
||||
def window():
|
||||
app = QApplication(sys.argv)
|
||||
w = QWidget()
|
||||
# Crea un pulsante e allegalo al widget w
|
||||
b = QPushButton(w)
|
||||
b.setText("Premimi")
|
||||
b.move(50, 50)
|
||||
# Indica a b di chiamare questa funzione quando si fa clic
|
||||
# notare la mancanza di "()" sulla chiamata di funzione
|
||||
b.clicked.connect(showdialog)
|
||||
w.setWindowTitle("PyQt Dialog")
|
||||
w.show()
|
||||
sys.exit(app.exec_())
|
||||
|
||||
# Questa funzione dovrebbe creare una finestra di dialogo con un pulsante
|
||||
# che aspetta di essere cliccato e quindi esce dal programma
|
||||
def showdialog():
|
||||
d = QDialog()
|
||||
b1 = QPushButton("ok", d)
|
||||
b1.move(50, 50)
|
||||
d.setWindowTitle("Dialog")
|
||||
# Questa modalità dice al popup di bloccare il genitore, mentre è attivo
|
||||
d.setWindowModality(Qt.ApplicationModal)
|
||||
# Al click vorrei che l'intero processo finisse
|
||||
b1.clicked.connect(sys.exit)
|
||||
d.exec_()
|
||||
|
||||
if __name__ == '__main__':
|
||||
window()
|
||||
```
|
1016
it-it/python3-it.html.markdown
Normal file
1016
it-it/python3-it.html.markdown
Normal file
File diff suppressed because it is too large
Load Diff
161
it-it/qt-it.html.markdown
Normal file
161
it-it/qt-it.html.markdown
Normal file
@ -0,0 +1,161 @@
|
||||
---
|
||||
category: tool
|
||||
tool: Qt Framework
|
||||
language: c++
|
||||
filename: learnqt.cpp
|
||||
contributors:
|
||||
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
|
||||
translators:
|
||||
- ["Ale46", "https://gihub.com/ale46"]
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*, ci sono diversi porting in altri linguaggi: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc.
|
||||
|
||||
**Qt** è ottimo per la creazione di applicazioni con interfaccia utente grafica (GUI). Questo tutorial descrive come farlo in *C++*.
|
||||
|
||||
```c++
|
||||
/*
|
||||
* Iniziamo classicamente
|
||||
*/
|
||||
|
||||
// tutte le intestazioni dal framework Qt iniziano con la lettera maiuscola 'Q'
|
||||
#include <QApplication>
|
||||
#include <QLineEdit>
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
// crea un oggetto per gestire le risorse a livello di applicazione
|
||||
QApplication app(argc, argv);
|
||||
|
||||
// crea un widget di campo di testo e lo mostra sullo schermo
|
||||
QLineEdit lineEdit("Hello world!");
|
||||
lineEdit.show();
|
||||
|
||||
// avvia il ciclo degli eventi dell'applicazione
|
||||
return app.exec();
|
||||
}
|
||||
```
|
||||
|
||||
La parte relativa alla GUI di **Qt** riguarda esclusivamente *widget* e le loro *connessioni*.
|
||||
|
||||
[LEGGI DI PIÙ SUI WIDGET](http://doc.qt.io/qt-5/qtwidgets-index.html)
|
||||
|
||||
```c++
|
||||
/*
|
||||
* Creiamo un'etichetta e un pulsante.
|
||||
* Un'etichetta dovrebbe apparire quando si preme un pulsante.
|
||||
*
|
||||
* Il codice Qt parla da solo.
|
||||
*/
|
||||
|
||||
#include <QApplication>
|
||||
#include <QDialog>
|
||||
#include <QVBoxLayout>
|
||||
#include <QPushButton>
|
||||
#include <QLabel>
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
QApplication app(argc, argv);
|
||||
|
||||
QDialog dialogWindow;
|
||||
dialogWindow.show();
|
||||
|
||||
// add vertical layout
|
||||
QVBoxLayout layout;
|
||||
dialogWindow.setLayout(&layout);
|
||||
|
||||
QLabel textLabel("Grazie per aver premuto quel pulsante");
|
||||
layout.addWidget(&textLabel);
|
||||
textLabel.hide();
|
||||
|
||||
QPushButton button("Premimi");
|
||||
layout.addWidget(&button);
|
||||
|
||||
// mostra l'etichetta nascosta quando viene premuto il pulsante
|
||||
QObject::connect(&button, &QPushButton::pressed,
|
||||
&textLabel, &QLabel::show);
|
||||
|
||||
return app.exec();
|
||||
}
|
||||
```
|
||||
|
||||
Si noti la parte relativa a *QObject::connect*. Questo metodo viene utilizzato per connettere *SEGNALI* di un oggetto agli *SLOTS* di un altro.
|
||||
|
||||
**I SEGNALI** vengono emessi quando certe cose accadono agli oggetti, come il segnale *premuto* che viene emesso quando l'utente preme sull'oggetto QPushButton.
|
||||
|
||||
**Gli slot** sono *azioni* che potrebbero essere eseguite in risposta ai segnali ricevuti.
|
||||
|
||||
[LEGGI DI PIÙ SU SLOT E SEGNALI](http://doc.qt.io/qt-5/signalsandslots.html)
|
||||
|
||||
|
||||
Successivamente, impariamo che non possiamo solo usare i widget standard, ma estendere il loro comportamento usando l'ereditarietà. Creiamo un pulsante e contiamo quante volte è stato premuto. A tale scopo definiamo la nostra classe *CounterLabel*. Deve essere dichiarato in un file separato a causa dell'architettura Qt specifica.
|
||||
|
||||
```c++
|
||||
// counterlabel.hpp
|
||||
|
||||
#ifndef COUNTERLABEL
|
||||
#define COUNTERLABEL
|
||||
|
||||
#include <QLabel>
|
||||
|
||||
class CounterLabel : public QLabel {
|
||||
Q_OBJECT // Macro definite da Qt che devono essere presenti in ogni widget personalizzato
|
||||
|
||||
public:
|
||||
CounterLabel() : counter(0) {
|
||||
setText("Il contatore non è stato ancora aumentato"); // metodo di QLabel
|
||||
}
|
||||
|
||||
public slots:
|
||||
// azione che verrà chiamata in risposta alla pressione del pulsante
|
||||
void increaseCounter() {
|
||||
setText(QString("Valore contatore: %1").arg(QString::number(++counter)));
|
||||
}
|
||||
|
||||
private:
|
||||
int counter;
|
||||
};
|
||||
|
||||
#endif // COUNTERLABEL
|
||||
```
|
||||
|
||||
```c++
|
||||
// main.cpp
|
||||
// Quasi uguale all'esempio precedente
|
||||
|
||||
#include <QApplication>
|
||||
#include <QDialog>
|
||||
#include <QVBoxLayout>
|
||||
#include <QPushButton>
|
||||
#include <QString>
|
||||
#include "counterlabel.hpp"
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
QApplication app(argc, argv);
|
||||
|
||||
QDialog dialogWindow;
|
||||
dialogWindow.show();
|
||||
|
||||
QVBoxLayout layout;
|
||||
dialogWindow.setLayout(&layout);
|
||||
|
||||
CounterLabel counterLabel;
|
||||
layout.addWidget(&counterLabel);
|
||||
|
||||
QPushButton button("Premimi ancora una volta");
|
||||
layout.addWidget(&button);
|
||||
QObject::connect(&button, &QPushButton::pressed,
|
||||
&counterLabel, &CounterLabel::increaseCounter);
|
||||
|
||||
return app.exec();
|
||||
}
|
||||
```
|
||||
|
||||
Questo è tutto! Ovviamente, il framework Qt è molto più grande della parte che è stata trattata in questo tutorial, quindi preparatevi a leggere e fare pratica.
|
||||
|
||||
## Ulteriori letture
|
||||
|
||||
- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html)
|
||||
- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html)
|
||||
|
||||
Buona fortuna e buon divertimento!
|
653
it-it/ruby-it.html.markdown
Normal file
653
it-it/ruby-it.html.markdown
Normal file
@ -0,0 +1,653 @@
|
||||
---
|
||||
language: ruby
|
||||
filename: learnruby-it.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"]
|
||||
- ["Corey Ward", "https://github.com/coreyward"]
|
||||
translators:
|
||||
- ["abonte", "https://github.com/abonte"]
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
```ruby
|
||||
# Questo è un commento
|
||||
|
||||
# In Ruby, (quasi) tutto è un oggetto.
|
||||
# Questo include i numeri...
|
||||
3.class #=> Integer
|
||||
|
||||
# ...stringhe...
|
||||
"Hello".class #=> String
|
||||
|
||||
# ...e anche i metodi!
|
||||
"Hello".method(:class).class #=> Method
|
||||
|
||||
# Qualche operazione aritmetica di base
|
||||
1 + 1 #=> 2
|
||||
8 - 1 #=> 7
|
||||
10 * 2 #=> 20
|
||||
35 / 5 #=> 7
|
||||
2 ** 5 #=> 32
|
||||
5 % 3 #=> 2
|
||||
|
||||
# Bitwise operators
|
||||
3 & 5 #=> 1
|
||||
3 | 5 #=> 7
|
||||
3 ^ 5 #=> 6
|
||||
|
||||
# L'aritmetica è solo zucchero sintattico
|
||||
# per chiamare il metodo di un oggetto
|
||||
1.+(3) #=> 4
|
||||
10.* 5 #=> 50
|
||||
100.methods.include?(:/) #=> true
|
||||
|
||||
# I valori speciali sono oggetti
|
||||
nil # equivalente a null in altri linguaggi
|
||||
true # vero
|
||||
false # falso
|
||||
|
||||
nil.class #=> NilClass
|
||||
true.class #=> TrueClass
|
||||
false.class #=> FalseClass
|
||||
|
||||
# Uguaglianza
|
||||
1 == 1 #=> true
|
||||
2 == 1 #=> false
|
||||
|
||||
# Disuguaglianza
|
||||
1 != 1 #=> false
|
||||
2 != 1 #=> true
|
||||
|
||||
# nil è l'unico valore, oltre a false, che è considerato 'falso'
|
||||
!!nil #=> false
|
||||
!!false #=> false
|
||||
!!0 #=> true
|
||||
!!"" #=> true
|
||||
|
||||
# Altri confronti
|
||||
1 < 10 #=> true
|
||||
1 > 10 #=> false
|
||||
2 <= 2 #=> true
|
||||
2 >= 2 #=> true
|
||||
|
||||
# Operatori di confronto combinati (ritorna '1' quando il primo argomento è più
|
||||
# grande, '-1' quando il secondo argomento è più grande, altrimenti '0')
|
||||
1 <=> 10 #=> -1
|
||||
10 <=> 1 #=> 1
|
||||
1 <=> 1 #=> 0
|
||||
|
||||
# Operatori logici
|
||||
true && false #=> false
|
||||
true || false #=> true
|
||||
|
||||
# Ci sono versioni alternative degli operatori logici con meno precedenza.
|
||||
# Sono usati come costrutti per il controllo di flusso per concatenare
|
||||
# insieme statement finché uno di essi ritorna true o false.
|
||||
|
||||
# `do_something_else` chiamato solo se `do_something` ha successo.
|
||||
do_something() and do_something_else()
|
||||
# `log_error` è chiamato solo se `do_something` fallisce.
|
||||
do_something() or log_error()
|
||||
|
||||
# Interpolazione di stringhe
|
||||
|
||||
placeholder = 'usare l\'interpolazione di stringhe'
|
||||
"Per #{placeholder} si usano stringhe con i doppi apici"
|
||||
#=> "Per usare l'interpolazione di stringhe si usano stringhe con i doppi apici"
|
||||
|
||||
# E' possibile combinare le stringhe usando `+`, ma non con gli altri tipi
|
||||
'hello ' + 'world' #=> "hello world"
|
||||
'hello ' + 3 #=> TypeError: can't convert Fixnum into String
|
||||
'hello ' + 3.to_s #=> "hello 3"
|
||||
"hello #{3}" #=> "hello 3"
|
||||
|
||||
# ...oppure combinare stringhe e operatori
|
||||
'ciao ' * 3 #=> "ciao ciao ciao "
|
||||
|
||||
# ...oppure aggiungere alla stringa
|
||||
'ciao' << ' mondo' #=> "ciao mondo"
|
||||
|
||||
# Per stampare a schermo e andare a capo
|
||||
puts "Sto stampando!"
|
||||
#=> Sto stampando!
|
||||
#=> nil
|
||||
|
||||
# Per stampare a schermo senza andare a capo
|
||||
print "Sto stampando!"
|
||||
#=> Sto stampando! => nil
|
||||
|
||||
# Variabili
|
||||
x = 25 #=> 25
|
||||
x #=> 25
|
||||
|
||||
# Notare che l'assegnamento ritorna il valore assegnato.
|
||||
# Questo significa che è possibile effettuare assegnamenti multipli:
|
||||
x = y = 10 #=> 10
|
||||
x #=> 10
|
||||
y #=> 10
|
||||
|
||||
# Per convenzione si usa lo snake_case per i nomi delle variabili
|
||||
snake_case = true
|
||||
|
||||
# Usare nomi delle variabili descrittivi
|
||||
path_to_project_root = '/buon/nome/'
|
||||
m = '/nome/scadente/'
|
||||
|
||||
# I simboli sono immutabili, costanti riusabili rappresentati internamente da
|
||||
# un valore intero. Sono spesso usati al posto delle stringhe per comunicare
|
||||
# specifici e significativi valori.
|
||||
|
||||
:pendente.class #=> Symbol
|
||||
|
||||
stato = :pendente
|
||||
|
||||
stato == :pendente #=> true
|
||||
|
||||
stato == 'pendente' #=> false
|
||||
|
||||
stato == :approvato #=> false
|
||||
|
||||
# Le stringhe possono essere convertite in simboli e viceversa:
|
||||
status.to_s #=> "pendente"
|
||||
"argon".to_sym #=> :argon
|
||||
|
||||
# Arrays
|
||||
|
||||
# Questo è un array
|
||||
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
|
||||
|
||||
# Gli array possono contenere diversi tipi di elementi
|
||||
[1, 'hello', false] #=> [1, "hello", false]
|
||||
|
||||
# Gli array possono essere indicizzati
|
||||
# Dall'inizio...
|
||||
array[0] #=> 1
|
||||
array.first #=> 1
|
||||
array[12] #=> nil
|
||||
|
||||
|
||||
# ...o dalla fine...
|
||||
array[-1] #=> 5
|
||||
array.last #=> 5
|
||||
|
||||
# With a start index and length
|
||||
# ...o con un indice di inzio e la lunghezza...
|
||||
array[2, 3] #=> [3, 4, 5]
|
||||
|
||||
# ...oppure con un intervallo.
|
||||
array[1..3] #=> [2, 3, 4]
|
||||
|
||||
# Invertire l'ordine degli elementi di un array
|
||||
a = [1,2,3]
|
||||
a.reverse! #=> [3,2,1]
|
||||
|
||||
# Come per l'aritmetica, l'accesso tramite [var]
|
||||
# è solo zucchero sintattico
|
||||
# per chiamare il metodo '[]'' di un oggetto
|
||||
array.[] 0 #=> 1
|
||||
array.[] 12 #=> nil
|
||||
|
||||
# Si può aggiungere un elemento all'array così
|
||||
array << 6 #=> [1, 2, 3, 4, 5, 6]
|
||||
# oppure così
|
||||
array.push(6) #=> [1, 2, 3, 4, 5, 6]
|
||||
|
||||
# Controllare se un elemento esiste in un array
|
||||
array.include?(1) #=> true
|
||||
|
||||
# Hash è un dizionario con coppie di chiave e valore
|
||||
# Un hash è denotato da parentesi graffe:
|
||||
hash = { 'colore' => 'verde', 'numero' => 5 }
|
||||
|
||||
hash.keys #=> ['colore', 'numero']
|
||||
|
||||
# E' possibile accedere all'hash tramite chiave:
|
||||
hash['colore'] #=> 'verde'
|
||||
hash['numero'] #=> 5
|
||||
|
||||
# Accedere all'hash con una chiave che non esiste ritorna nil:
|
||||
hash['nothing here'] #=> nil
|
||||
|
||||
# Quando si usano simboli come chiavi di un hash, si possono utilizzare
|
||||
# queste sintassi:
|
||||
|
||||
hash = { :defcon => 3, :action => true }
|
||||
hash.keys #=> [:defcon, :action]
|
||||
# oppure
|
||||
hash = { defcon: 3, action: true }
|
||||
hash.keys #=> [:defcon, :action]
|
||||
|
||||
# Controllare l'esistenza di una chiave o di un valore in un hash
|
||||
new_hash.key?(:defcon) #=> true
|
||||
new_hash.value?(3) #=> true
|
||||
|
||||
# Suggerimento: sia gli array che gli hash sono enumerabili!
|
||||
# Entrambi possiedono metodi utili come each, map, count e altri.
|
||||
|
||||
# Strutture di controllo
|
||||
|
||||
#Condizionali
|
||||
if true
|
||||
'if statement'
|
||||
elsif false
|
||||
'else if, opzionale'
|
||||
else
|
||||
'else, opzionale'
|
||||
end
|
||||
|
||||
#Cicli
|
||||
# In Ruby, i tradizionali cicli `for` non sono molto comuni. Questi semplici
|
||||
# cicli, invece, sono implementati con un enumerable, usando `each`:
|
||||
(1..5).each do |contatore|
|
||||
puts "iterazione #{contatore}"
|
||||
end
|
||||
|
||||
# Esso è equivalente a questo ciclo, il quale è inusuale da vedere in Ruby:
|
||||
for contatore in 1..5
|
||||
puts "iterazione #{contatore}"
|
||||
end
|
||||
|
||||
# Il costrutto `do |variable| ... end` è chiamato 'blocco'. I blocchi
|
||||
# sono simili alle lambda, funzioni anonime o closure che si trovano in altri
|
||||
# linguaggi di programmazione. Essi possono essere passati come oggetti,
|
||||
# chiamati o allegati come metodi.
|
||||
#
|
||||
# Il metodo 'each' di un intervallo (range) esegue il blocco una volta
|
||||
# per ogni elemento dell'intervallo.
|
||||
# Al blocco è passato un contatore come parametro.
|
||||
|
||||
# E' possibile inglobare il blocco fra le parentesi graffe
|
||||
(1..5).each { |contatore| puts "iterazione #{contatore}" }
|
||||
|
||||
# Il contenuto delle strutture dati può essere iterato usando "each".
|
||||
array.each do |elemento|
|
||||
puts "#{elemento} è parte dell'array"
|
||||
end
|
||||
hash.each do |chiave, valore|
|
||||
puts "#{chiave} è #{valore}"
|
||||
end
|
||||
|
||||
# If you still need an index you can use 'each_with_index' and define an index
|
||||
# variable
|
||||
# Se comunque si vuole un indice, si può usare "each_with_index" e definire
|
||||
# una variabile che contiene l'indice
|
||||
array.each_with_index do |elemento, indice|
|
||||
puts "#{elemento} è il numero #{index} nell'array"
|
||||
end
|
||||
|
||||
contatore = 1
|
||||
while contatore <= 5 do
|
||||
puts "iterazione #{contatore}"
|
||||
contatore += 1
|
||||
end
|
||||
#=> iterazione 1
|
||||
#=> iterazione 2
|
||||
#=> iterazione 3
|
||||
#=> iterazione 4
|
||||
#=> iterazione 5
|
||||
|
||||
# Esistono in Ruby ulteriori funzioni per fare i cicli,
|
||||
# come per esempio 'map', 'reduce', 'inject' e altri.
|
||||
# Nel caso di 'map', esso prende l'array sul quale si sta iterando, esegue
|
||||
# le istruzioni definite nel blocco, e ritorna un array completamente nuovo.
|
||||
array = [1,2,3,4,5]
|
||||
doubled = array.map do |elemento|
|
||||
elemento * 2
|
||||
end
|
||||
puts doubled
|
||||
#=> [2,4,6,8,10]
|
||||
puts array
|
||||
#=> [1,2,3,4,5]
|
||||
|
||||
# Costrutto "case"
|
||||
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' può usare anche gli intervalli
|
||||
grade = 82
|
||||
case grade
|
||||
when 90..100
|
||||
puts 'Hooray!'
|
||||
when 80...90
|
||||
puts 'OK job'
|
||||
else
|
||||
puts 'You failed!'
|
||||
end
|
||||
#=> "OK job"
|
||||
|
||||
# Gestione delle eccezioni
|
||||
begin
|
||||
# codice che può sollevare un eccezione
|
||||
raise NoMemoryError, 'Esaurita la memoria.'
|
||||
rescue NoMemoryError => exception_variable
|
||||
puts 'NoMemoryError è stato sollevato.', exception_variable
|
||||
rescue RuntimeError => other_exception_variable
|
||||
puts 'RuntimeError è stato sollvato.'
|
||||
else
|
||||
puts 'Questo viene eseguito se nessuna eccezione è stata sollevata.'
|
||||
ensure
|
||||
puts 'Questo codice viene sempre eseguito a prescindere.'
|
||||
end
|
||||
|
||||
# Metodi
|
||||
|
||||
def double(x)
|
||||
x * 2
|
||||
end
|
||||
|
||||
# Metodi (e blocchi) ritornano implicitamente il valore dell'ultima istruzione
|
||||
double(2) #=> 4
|
||||
|
||||
# Le parentesi sono opzionali dove l'interpolazione è inequivocabile
|
||||
double 3 #=> 6
|
||||
|
||||
double double 3 #=> 12
|
||||
|
||||
def sum(x, y)
|
||||
x + y
|
||||
end
|
||||
|
||||
# Gli argomenit dei metodi sono separati dalla virgola
|
||||
sum 3, 4 #=> 7
|
||||
|
||||
sum sum(3, 4), 5 #=> 12
|
||||
|
||||
# yield
|
||||
# Tutti i metodi hanno un implicito e opzionale parametro del blocco.
|
||||
# Esso può essere chiamato con la parola chiave 'yield'.
|
||||
|
||||
def surround
|
||||
puts '{'
|
||||
yield
|
||||
puts '}'
|
||||
end
|
||||
|
||||
surround { puts 'hello world' }
|
||||
|
||||
# {
|
||||
# hello world
|
||||
# }
|
||||
|
||||
# I blocchi possono essere convertiti in 'proc', il quale racchiude il blocco
|
||||
# e gli permette di essere passato ad un altro metodo, legato ad uno scope
|
||||
# differente o modificato. Questo è molto comune nella lista parametri del
|
||||
# metodo, dove è frequente vedere il parametro '&block' in coda. Esso accetta
|
||||
# il blocco, se ne è stato passato uno, e lo converte in un 'Proc'.
|
||||
# Qui la denominazione è una convenzione; funzionerebbe anche con '&ananas'.
|
||||
def guests(&block)
|
||||
block.class #=> Proc
|
||||
block.call(4)
|
||||
end
|
||||
|
||||
# Il metodo 'call' del Proc è simile allo 'yield' quando è presente un blocco.
|
||||
# Gli argomenti passati a 'call' sono inoltrati al blocco come argomenti:
|
||||
|
||||
guests { |n| "You have #{n} guests." }
|
||||
# => "You have 4 guests."
|
||||
|
||||
# L'operatore splat ("*") converte una lista di argomenti in un array
|
||||
def guests(*array)
|
||||
array.each { |guest| puts guest }
|
||||
end
|
||||
|
||||
# Destrutturazione
|
||||
|
||||
# Ruby destruttura automaticamente gli array in assegnamento
|
||||
# a variabili multiple:
|
||||
a, b, c = [1, 2, 3]
|
||||
a #=> 1
|
||||
b #=> 2
|
||||
c #=> 3
|
||||
|
||||
# In alcuni casi si usa l'operatore splat ("*") per destrutturare
|
||||
# un array in una lista.
|
||||
classifica_concorrenti = ["John", "Sally", "Dingus", "Moe", "Marcy"]
|
||||
|
||||
def migliore(primo, secondo, terzo)
|
||||
puts "I vincitori sono #{primo}, #{secondo}, e #{terzo}."
|
||||
end
|
||||
|
||||
migliore *classifica_concorrenti.first(3)
|
||||
#=> I vincitori sono John, Sally, e Dingus.
|
||||
|
||||
# The splat operator can also be used in parameters:
|
||||
def migliore(primo, secondo, terzo, *altri)
|
||||
puts "I vincitori sono #{primo}, #{secondo}, e #{terzo}."
|
||||
puts "C'erano altri #{altri.count} partecipanti."
|
||||
end
|
||||
|
||||
migliore *classifica_concorrenti
|
||||
#=> I vincitori sono John, Sally, e Dingus.
|
||||
#=> C'erano altri 2 partecipanti.
|
||||
|
||||
# Per convenzione, tutti i metodi che ritornano un booleano terminano
|
||||
# con un punto interrogativo
|
||||
5.even? #=> false
|
||||
5.odd? #=> true
|
||||
|
||||
# Per convenzione, se il nome di un metodo termina con un punto esclamativo,
|
||||
# esso esegue qualcosa di distruttivo. Molti metodi hanno una versione con '!'
|
||||
# per effettuare una modifiche, e una versione senza '!' che ritorna
|
||||
# una versione modificata.
|
||||
nome_azienda = "Dunder Mifflin"
|
||||
nome_azienda.upcase #=> "DUNDER MIFFLIN"
|
||||
nome_azienda #=> "Dunder Mifflin"
|
||||
# Questa volta modifichiamo nome_azienda
|
||||
nome_azienda.upcase! #=> "DUNDER MIFFLIN"
|
||||
nome_azienda #=> "DUNDER MIFFLIN"
|
||||
|
||||
# Classi
|
||||
|
||||
# Definire una classe con la parola chiave class
|
||||
class Umano
|
||||
|
||||
# Una variabile di classe. E' condivisa da tutte le istance di questa classe.
|
||||
@@specie = 'H. sapiens'
|
||||
|
||||
# Inizializzatore di base
|
||||
def initialize(nome, eta = 0)
|
||||
# Assegna il valore dell'argomento alla variabile dell'istanza "nome"
|
||||
@nome = nome
|
||||
# Se l'età non è fornita, verrà assegnato il valore di default indicato
|
||||
# nella lista degli argomenti
|
||||
@eta = eta
|
||||
end
|
||||
|
||||
# Metodo setter di base
|
||||
def nome=(nome)
|
||||
@nome = nome
|
||||
end
|
||||
|
||||
# Metodo getter di base
|
||||
def nome
|
||||
@nome
|
||||
end
|
||||
|
||||
# Le funzionalità di cui sopra posso essere incapsulate usando
|
||||
# il metodo attr_accessor come segue
|
||||
attr_accessor :nome
|
||||
|
||||
# Getter/setter possono anche essere creati individualmente
|
||||
attr_reader :nome
|
||||
attr_writer :nome
|
||||
|
||||
# Un metodo della classe usa 'self' per distinguersi dai metodi dell'istanza.
|
||||
# Può essere richimato solo dalla classe, non dall'istanza.
|
||||
def self.say(msg)
|
||||
puts msg
|
||||
end
|
||||
|
||||
def specie
|
||||
@@specie
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Instanziare una classe
|
||||
jim = Umano.new('Jim Halpert')
|
||||
|
||||
dwight = Umano.new('Dwight K. Schrute')
|
||||
|
||||
# Chiamiamo qualche metodo
|
||||
jim.specie #=> "H. sapiens"
|
||||
jim.nome #=> "Jim Halpert"
|
||||
jim.nome = "Jim Halpert II" #=> "Jim Halpert II"
|
||||
jim.nome #=> "Jim Halpert II"
|
||||
dwight.specie #=> "H. sapiens"
|
||||
dwight.nome #=> "Dwight K. Schrute"
|
||||
|
||||
# Chiamare un metodo della classe
|
||||
Umano.say('Ciao') #=> "Ciao"
|
||||
|
||||
# La visibilità della variabile (variable's scope) è determinata dal modo
|
||||
# in cui le viene assegnato il nome.
|
||||
# Variabili che iniziano con $ hanno uno scope globale
|
||||
$var = "Sono una variabile globale"
|
||||
defined? $var #=> "global-variable"
|
||||
|
||||
# Variabili che inziano con @ hanno a livello dell'istanza
|
||||
@var = "Sono una variabile dell'istanza"
|
||||
defined? @var #=> "instance-variable"
|
||||
|
||||
# Variabili che iniziano con @@ hanno una visibilità a livello della classe
|
||||
@@var = "Sono una variabile della classe"
|
||||
defined? @@var #=> "class variable"
|
||||
|
||||
# Variabili che iniziano con una lettera maiuscola sono costanti
|
||||
Var = "Sono una costante"
|
||||
defined? Var #=> "constant"
|
||||
|
||||
# Anche una classe è un oggetto in ruby. Quindi la classe può avere
|
||||
# una variabile dell'istanza. Le variabili della classe sono condivise
|
||||
# fra la classe e tutti i suoi discendenti.
|
||||
|
||||
# Classe base
|
||||
class Umano
|
||||
@@foo = 0
|
||||
|
||||
def self.foo
|
||||
@@foo
|
||||
end
|
||||
|
||||
def self.foo=(value)
|
||||
@@foo = value
|
||||
end
|
||||
end
|
||||
|
||||
# Classe derivata
|
||||
class Lavoratore < Umano
|
||||
end
|
||||
|
||||
Umano.foo #=> 0
|
||||
Lavoratore.foo #=> 0
|
||||
|
||||
Umano.foo = 2 #=> 2
|
||||
Lavoratore.foo #=> 2
|
||||
|
||||
# La variabile dell'istanza della classe non è condivisa dai discendenti.
|
||||
|
||||
class Umano
|
||||
@bar = 0
|
||||
|
||||
def self.bar
|
||||
@bar
|
||||
end
|
||||
|
||||
def self.bar=(value)
|
||||
@bar = value
|
||||
end
|
||||
end
|
||||
|
||||
class Dottore < Umano
|
||||
end
|
||||
|
||||
Umano.bar #=> 0
|
||||
Dottore.bar #=> nil
|
||||
|
||||
module EsempioModulo
|
||||
def foo
|
||||
'foo'
|
||||
end
|
||||
end
|
||||
|
||||
# Includere moduli vincola i suoi metodi all'istanza della classe.
|
||||
# Estendere moduli vincola i suoi metodi alla classe stessa.
|
||||
class Persona
|
||||
include EsempioModulo
|
||||
end
|
||||
|
||||
class Libro
|
||||
extend EsempioModulo
|
||||
end
|
||||
|
||||
Persona.foo #=> NoMethodError: undefined method `foo' for Person:Class
|
||||
Persona.new.foo #=> 'foo'
|
||||
Libro.foo #=> 'foo'
|
||||
Libro.new.foo #=> NoMethodError: undefined method `foo'
|
||||
|
||||
# Callbacks sono eseguiti quand si include o estende un modulo
|
||||
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'
|
||||
```
|
||||
|
||||
## Ulteriori risorse
|
||||
|
||||
- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Una variante di questa guida con esercizi nel browser.
|
||||
- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Imparare Ruby attraverso una serie di tutorial interattivi.
|
||||
- [Official Documentation](http://ruby-doc.org/core)
|
||||
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
|
||||
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una passata [edizione libera](http://ruby-doc.com/docs/ProgrammingRuby/) è disponibile online.
|
||||
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
|
||||
- [Try Ruby](http://tryruby.org) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser.
|
276
it-it/toml-it.html.markdown
Normal file
276
it-it/toml-it.html.markdown
Normal file
@ -0,0 +1,276 @@
|
||||
---
|
||||
language: toml
|
||||
filename: learntoml-it.toml
|
||||
contributors:
|
||||
- ["Alois de Gouvello", "https://github.com/aloisdg"]
|
||||
translators:
|
||||
- ["Christian Grasso", "https://grasso.io"]
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la
|
||||
serializzazione di dati, progettato per i file di configurazione.
|
||||
|
||||
È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile
|
||||
per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza
|
||||
semplice nella maggior parte dei linguaggi di programmazione, in quanto è
|
||||
progettato per essere tradotto senza ambiguità in una hash table.
|
||||
|
||||
Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è
|
||||
ancora stabile. Questo documento utilizza TOML 0.4.0.
|
||||
|
||||
```toml
|
||||
# I commenti in TOML sono fatti così.
|
||||
|
||||
################
|
||||
# TIPI SCALARI #
|
||||
################
|
||||
|
||||
# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa,
|
||||
# anche chiamata dizionario, hash o oggetto in altri linguaggi.
|
||||
|
||||
# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga,
|
||||
# eccetto per alcuni tipi di valori.
|
||||
key = "value"
|
||||
stringa = "ciao"
|
||||
numero = 42
|
||||
float = 3.14
|
||||
boolean = true
|
||||
data = 1979-05-27T07:32:00-08:00
|
||||
notazScientifica = 1e+12
|
||||
"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure '
|
||||
"la key può contenere" = "lettere, numeri, underscore e trattini"
|
||||
|
||||
############
|
||||
# Stringhe #
|
||||
############
|
||||
|
||||
# Le stringhe possono contenere solo caratteri UTF-8 validi.
|
||||
# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze
|
||||
# di escape compatte. Ad esempio, \t corrisponde al TAB.
|
||||
stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"."
|
||||
|
||||
stringaMultiriga = """
|
||||
Racchiusa da tre virgolette doppie all'inizio e
|
||||
alla fine - consente di andare a capo."""
|
||||
|
||||
stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.'
|
||||
|
||||
stringaMultirigaLiteral = '''
|
||||
Racchiusa da tre virgolette singole all'inizio e
|
||||
alla fine - consente di andare a capo.
|
||||
Anche in questo caso non si può fare escape.
|
||||
Il primo ritorno a capo viene eliminato.
|
||||
Tutti gli altri spazi aggiuntivi
|
||||
vengono mantenuti.
|
||||
'''
|
||||
|
||||
# Per i dati binari è consigliabile utilizzare Base64 e
|
||||
# gestirli manualmente dall'applicazione.
|
||||
|
||||
##########
|
||||
# Interi #
|
||||
##########
|
||||
|
||||
## Gli interi possono avere o meno un segno (+, -).
|
||||
## Non si possono inserire zero superflui all'inizio.
|
||||
## Non è possibile inoltre utilizzare valori numerici
|
||||
## non rappresentabili con una sequenza di cifre.
|
||||
int1 = +42
|
||||
int2 = 0
|
||||
int3 = -21
|
||||
|
||||
## Puoi utilizzare gli underscore per migliorare la leggibilità.
|
||||
## Fai attenzione a non inserirne due di seguito.
|
||||
int4 = 5_349_221
|
||||
int5 = 1_2_3_4_5 # VALIDO, ma da evitare
|
||||
|
||||
#########
|
||||
# Float #
|
||||
#########
|
||||
|
||||
# I float permettono di rappresentare numeri decimali.
|
||||
flt1 = 3.1415
|
||||
flt2 = -5e6
|
||||
flt3 = 6.626E-34
|
||||
|
||||
###########
|
||||
# Boolean #
|
||||
###########
|
||||
|
||||
# I valori boolean (true/false) devono essere scritti in minuscolo.
|
||||
bool1 = true
|
||||
bool2 = false
|
||||
|
||||
############
|
||||
# Data/ora #
|
||||
############
|
||||
|
||||
data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC)
|
||||
data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset
|
||||
|
||||
######################
|
||||
# TIPI DI COLLECTION #
|
||||
######################
|
||||
|
||||
#########
|
||||
# Array #
|
||||
#########
|
||||
|
||||
array1 = [ 1, 2, 3 ]
|
||||
array2 = [ "Le", "virgole", "sono", "delimitatori" ]
|
||||
array3 = [ "Non", "unire", "tipi", "diversi" ]
|
||||
array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ]
|
||||
array5 = [
|
||||
"Gli spazi vuoti", "sono", "ignorati"
|
||||
]
|
||||
|
||||
###########
|
||||
# Tabelle #
|
||||
###########
|
||||
|
||||
# Le tabelle (o hash table o dizionari) sono collection di coppie key/value.
|
||||
# Iniziano con un nome tra parentesi quadre su una linea separata.
|
||||
# Le tabelle vuote (senza alcun valore) sono valide.
|
||||
[tabella]
|
||||
|
||||
# Tutti i valori che si trovano sotto il nome della tabella
|
||||
# appartengono alla tabella stessa (finchè non ne viene creata un'altra).
|
||||
# L'ordine di questi valori non è garantito.
|
||||
[tabella-1]
|
||||
key1 = "una stringa"
|
||||
key2 = 123
|
||||
|
||||
[tabella-2]
|
||||
key1 = "un'altra stringa"
|
||||
key2 = 456
|
||||
|
||||
# Utilizzando i punti è possibile creare delle sottotabelle.
|
||||
# Ogni parte suddivisa dai punti segue le regole delle key per il nome.
|
||||
[tabella-3."sotto.tabella"]
|
||||
key1 = "prova"
|
||||
|
||||
# Ecco l'equivalente JSON della tabella precedente:
|
||||
# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } }
|
||||
|
||||
# Gli spazi non vengono considerati, ma è consigliabile
|
||||
# evitare di usare spazi superflui.
|
||||
[a.b.c] # consigliato
|
||||
[ d.e.f ] # identico a [d.e.f]
|
||||
|
||||
# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella.
|
||||
# [x] queste
|
||||
# [x.y] non
|
||||
# [x.y.z] servono
|
||||
[x.y.z.w] # per creare questa tabella
|
||||
|
||||
# Se non è stata già creata prima, puoi anche creare
|
||||
# una tabella superiore più avanti.
|
||||
[a.b]
|
||||
c = 1
|
||||
|
||||
[a]
|
||||
d = 2
|
||||
|
||||
# Non puoi definire una key o una tabella più di una volta.
|
||||
|
||||
# ERRORE
|
||||
[a]
|
||||
b = 1
|
||||
|
||||
[a]
|
||||
c = 2
|
||||
|
||||
# ERRORE
|
||||
[a]
|
||||
b = 1
|
||||
|
||||
[a.b]
|
||||
c = 2
|
||||
|
||||
# I nomi delle tabelle non possono essere vuoti.
|
||||
[] # NON VALIDO
|
||||
[a.] # NON VALIDO
|
||||
[a..b] # NON VALIDO
|
||||
[.b] # NON VALIDO
|
||||
[.] # NON VALIDO
|
||||
|
||||
##################
|
||||
# Tabelle inline #
|
||||
##################
|
||||
|
||||
tabelleInline = { racchiuseData = "{ e }", rigaSingola = true }
|
||||
punto = { x = 1, y = 2 }
|
||||
|
||||
####################
|
||||
# Array di tabelle #
|
||||
####################
|
||||
|
||||
# Un array di tabelle può essere creato utilizzando due parentesi quadre.
|
||||
# Tutte le tabelle con questo nome saranno elementi dell'array.
|
||||
# Gli elementi vengono inseriti nell'ordine in cui si trovano.
|
||||
|
||||
[[prodotti]]
|
||||
nome = "array di tabelle"
|
||||
sku = 738594937
|
||||
tabelleVuoteValide = true
|
||||
|
||||
[[prodotti]]
|
||||
|
||||
[[prodotti]]
|
||||
nome = "un altro item"
|
||||
sku = 284758393
|
||||
colore = "grigio"
|
||||
|
||||
# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie
|
||||
# parentesi quadre apparterranno alla tabella più vicina sopra di esse.
|
||||
|
||||
[[frutta]]
|
||||
nome = "mela"
|
||||
|
||||
[frutto.geometria]
|
||||
forma = "sferica"
|
||||
nota = "Sono una proprietà del frutto"
|
||||
|
||||
[[frutto.colore]]
|
||||
nome = "rosso"
|
||||
nota = "Sono un oggetto di un array dentro mela"
|
||||
|
||||
[[frutto.colore]]
|
||||
nome = "verde"
|
||||
nota = "Sono nello stesso array di rosso"
|
||||
|
||||
[[frutta]]
|
||||
nome = "banana"
|
||||
|
||||
[[frutto.colore]]
|
||||
nome = "giallo"
|
||||
nota = "Anche io sono un oggetto di un array, ma dentro banana"
|
||||
```
|
||||
|
||||
Ecco l'equivalente JSON dell'ultima tabella:
|
||||
|
||||
```json
|
||||
{
|
||||
"frutta": [
|
||||
{
|
||||
"nome": "mela",
|
||||
"geometria": { "forma": "sferica", "nota": "..."},
|
||||
"colore": [
|
||||
{ "nome": "rosso", "nota": "..." },
|
||||
{ "nome": "verde", "nota": "..." }
|
||||
]
|
||||
},
|
||||
{
|
||||
"nome": "banana",
|
||||
"colore": [
|
||||
{ "nome": "giallo", "nota": "..." }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Altre risorse
|
||||
|
||||
+ [Repository ufficiale di TOML](https://github.com/toml-lang/toml)
|
227
it-it/typescript-it.html.markdown
Normal file
227
it-it/typescript-it.html.markdown
Normal file
@ -0,0 +1,227 @@
|
||||
---
|
||||
language: TypeScript
|
||||
contributors:
|
||||
- ["Philippe Vlérick", "https://github.com/pvlerick"]
|
||||
translators:
|
||||
- ["Christian Grasso", "https://grasso.io"]
|
||||
filename: learntypescript-it.ts
|
||||
lang: it-it
|
||||
---
|
||||
|
||||
TypeScript è un linguaggio basato su JavaScript che punta a rendere il codice
|
||||
più scalabile introducendo concetti quali le classi, i moduli, le interface,
|
||||
e i generics.
|
||||
Poichè TypeScript è un superset di JavaScript, è possibile sfruttare le sue
|
||||
funzionalità anche in progetti esistenti: il codice JavaScript valido è anche
|
||||
valido in TypeScript. Il compilatore di TypeScript genera codice JavaScript.
|
||||
|
||||
Questo articolo si concentrerà solo sulle funzionalità aggiuntive di TypeScript.
|
||||
|
||||
Per testare il compilatore, puoi utilizzare il
|
||||
[Playground](http://www.typescriptlang.org/Playground), dove potrai scrivere
|
||||
codice TypeScript e visualizzare l'output in JavaScript.
|
||||
|
||||
```ts
|
||||
// TypeScript ha tre tipi di base
|
||||
let completato: boolean = false;
|
||||
let righe: number = 42;
|
||||
let nome: string = "Andrea";
|
||||
|
||||
// Il tipo può essere omesso se è presente un assegnamento a scalari/literal
|
||||
let completato = false;
|
||||
let righe = 42;
|
||||
let nome = "Andrea";
|
||||
|
||||
// Il tipo "any" indica che la variabile può essere di qualsiasi tipo
|
||||
let qualsiasi: any = 4;
|
||||
qualsiasi = "oppure una stringa";
|
||||
qualsiasi = false; // o magari un boolean
|
||||
|
||||
// Usa la keyword "const" per le costanti
|
||||
const numeroViteGatti = 9;
|
||||
numeroViteGatti = 1; // Errore
|
||||
|
||||
// Per gli array, puoi usare l'apposito tipo o la versione con i generics
|
||||
let lista: number[] = [1, 2, 3];
|
||||
let lista: Array<number> = [1, 2, 3];
|
||||
|
||||
// Per le enumerazioni:
|
||||
enum Colore { Rosso, Verde, Blu };
|
||||
let c: Colore = Colore.Verde;
|
||||
|
||||
// Infine, "void" viene utilizzato per le funzioni che non restituiscono valori
|
||||
function avviso(): void {
|
||||
alert("Sono un piccolo avviso fastidioso!");
|
||||
}
|
||||
|
||||
// Le funzioni supportano la sintassi "a freccia" (lambda) e supportano la type
|
||||
// inference, cioè per scalari/literal non c'è bisogno di specificare il tipo
|
||||
|
||||
// Tutte le seguenti funzioni sono equivalenti, e il compilatore genererà
|
||||
// lo stesso codice JavaScript per ognuna di esse
|
||||
let f1 = function (i: number): number { return i * i; }
|
||||
// Type inference
|
||||
let f2 = function (i: number) { return i * i; }
|
||||
// Sintassi lambda
|
||||
let f3 = (i: number): number => { return i * i; }
|
||||
// Sintassi lambda + type inference
|
||||
let f4 = (i: number) => { return i * i; }
|
||||
// Sintassi lambda + type inference + sintassi abbreviata (senza return)
|
||||
let f5 = (i: number) => i * i;
|
||||
|
||||
// Le interfacce sono strutturali, e qualunque oggetto con le stesse proprietà
|
||||
// di un'interfaccia è compatibile con essa
|
||||
interface Persona {
|
||||
nome: string;
|
||||
// Proprietà opzionale, indicata con "?"
|
||||
anni?: number;
|
||||
// Funzioni
|
||||
saluta(): void;
|
||||
}
|
||||
|
||||
// Oggetto che implementa l'interfaccia Persona
|
||||
// È una Persona valida poichè implementa tutta le proprietà non opzionali
|
||||
let p: Persona = { nome: "Bobby", saluta: () => { } };
|
||||
// Naturalmente può avere anche le proprietà opzionali:
|
||||
let pValida: Persona = { nome: "Bobby", anni: 42, saluta: () => { } };
|
||||
// Questa invece NON è una Persona, poichè il tipo di "anni" è sbagliato
|
||||
let pNonValida: Persona = { nome: "Bobby", anni: true };
|
||||
|
||||
// Le interfacce possono anche descrivere una funzione
|
||||
interface SearchFunc {
|
||||
(source: string, subString: string): boolean;
|
||||
}
|
||||
// I nomi dei parametri non sono rilevanti: vengono controllati solo i tipi
|
||||
let ricerca: SearchFunc;
|
||||
ricerca = function (src: string, sub: string) {
|
||||
return src.search(sub) != -1;
|
||||
}
|
||||
|
||||
// Classi - i membri sono pubblici di default
|
||||
class Punto {
|
||||
// Proprietà
|
||||
x: number;
|
||||
|
||||
// Costruttore - in questo caso la keyword "public" può generare in automatico
|
||||
// il codice per l'inizializzazione di una variabile.
|
||||
// In questo esempio, verrà creata la variabile y in modo identico alla x, ma
|
||||
// con meno codice. Sono supportati anche i valori di default.
|
||||
constructor(x: number, public y: number = 0) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
// Funzioni
|
||||
dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
||||
|
||||
// Membri statici
|
||||
static origine = new Point(0, 0);
|
||||
}
|
||||
|
||||
// Le classi possono anche implementare esplicitamente delle interfacce.
|
||||
// Il compilatore restituirà un errore nel caso in cui manchino delle proprietà.
|
||||
class PersonaDiRiferimento implements Persona {
|
||||
nome: string
|
||||
saluta() {}
|
||||
}
|
||||
|
||||
let p1 = new Punto(10, 20);
|
||||
let p2 = new Punto(25); // y = 0
|
||||
|
||||
// Inheritance
|
||||
class Punto3D extends Punto {
|
||||
constructor(x: number, y: number, public z: number = 0) {
|
||||
super(x, y); // La chiamata esplicita a super è obbligatoria
|
||||
}
|
||||
|
||||
// Sovrascrittura
|
||||
dist() {
|
||||
let d = super.dist();
|
||||
return Math.sqrt(d * d + this.z * this.z);
|
||||
}
|
||||
}
|
||||
|
||||
// Moduli - "." può essere usato come separatore per i sottomoduli
|
||||
module Geometria {
|
||||
export class Quadrato {
|
||||
constructor(public lato: number = 0) { }
|
||||
|
||||
area() {
|
||||
return Math.pow(this.lato, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let s1 = new Geometria.Quadrato(5);
|
||||
|
||||
// Alias locale per un modulo
|
||||
import G = Geometria;
|
||||
|
||||
let s2 = new G.Quadrato(10);
|
||||
|
||||
// Generics
|
||||
// Classi
|
||||
class Tuple<T1, T2> {
|
||||
constructor(public item1: T1, public item2: T2) {
|
||||
}
|
||||
}
|
||||
|
||||
// Interfacce
|
||||
interface Pair<T> {
|
||||
item1: T;
|
||||
item2: T;
|
||||
}
|
||||
|
||||
// E funzioni
|
||||
let pairToTuple = function <T>(p: Pair<T>) {
|
||||
return new Tuple(p.item1, p.item2);
|
||||
};
|
||||
|
||||
let tuple = pairToTuple({ item1: "hello", item2: "world" });
|
||||
|
||||
// Interpolazione con le template string (definite con i backtick)
|
||||
let nome = 'Tyrone';
|
||||
let saluto = `Ciao ${name}, come stai?`
|
||||
// Possono anche estendersi su più righe
|
||||
let multiriga = `Questo è un esempio
|
||||
di stringa multiriga.`;
|
||||
|
||||
// La keyword "readonly" rende un membro di sola lettura
|
||||
interface Persona {
|
||||
readonly nome: string;
|
||||
readonly anni: number;
|
||||
}
|
||||
|
||||
var p1: Persona = { nome: "Tyrone", anni: 42 };
|
||||
p1.anni = 25; // Errore, p1.anni è readonly
|
||||
|
||||
var p2 = { nome: "John", anni: 60 };
|
||||
var p3: Person = p2; // Ok, abbiamo creato una versione readonly di p2
|
||||
p3.anni = 35; // Errore, p3.anni è readonly
|
||||
p2.anni = 45; // Compila, ma cambia anche p3.anni per via dell'aliasing!
|
||||
|
||||
class Macchina {
|
||||
readonly marca: string;
|
||||
readonly modello: string;
|
||||
readonly anno = 2018;
|
||||
|
||||
constructor() {
|
||||
// Possiamo anche assegnare nel constructor
|
||||
this.marca = "Marca sconosciuta";
|
||||
this.modello = "Modello sconosciuto";
|
||||
}
|
||||
}
|
||||
|
||||
let numeri: Array<number> = [0, 1, 2, 3, 4];
|
||||
let altriNumeri: ReadonlyArray<number> = numbers;
|
||||
altriNumeri[5] = 5; // Errore, gli elementi sono readonly
|
||||
altriNumeri.push(5); // Errore, il metodo push non esiste (modifica l'array)
|
||||
altriNumeri.length = 3; // Errore, length è readonly
|
||||
numeri = altriNumeri; // Errore, i metodi di modifica non esistono
|
||||
```
|
||||
|
||||
## Altre risorse
|
||||
* [Sito ufficiale di TypeScript](http://www.typescriptlang.org/)
|
||||
* [Specifica di TypeScript](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)
|
||||
* [Anders Hejlsberg - Introducing TypeScript su Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
|
||||
* [TypeScript su GitHub](https://github.com/Microsoft/TypeScript)
|
||||
* [Definitely Typed - definizioni per le librerie](http://definitelytyped.org/)
|
@ -11,6 +11,7 @@ contributors:
|
||||
- ["Michael Dähnert", "https://github.com/JaXt0r"]
|
||||
- ["Rob Rose", "https://github.com/RobRoseKnows"]
|
||||
- ["Sean Nam", "https://github.com/seannam"]
|
||||
- ["Shawn M. Hanes", "https://github.com/smhanes15"]
|
||||
filename: LearnJava.java
|
||||
---
|
||||
|
||||
@ -44,8 +45,6 @@ import java.util.ArrayList;
|
||||
// Import all classes inside of java.security package
|
||||
import java.security.*;
|
||||
|
||||
// Each .java file contains one outer-level public class, with the same name
|
||||
// as the file.
|
||||
public class LearnJava {
|
||||
|
||||
// In order to run a java program, it must have a main method as an entry
|
||||
@ -860,6 +859,108 @@ public class EnumTest {
|
||||
// The enum body can include methods and other fields.
|
||||
// You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
|
||||
|
||||
// Getting Started with Lambda Expressions
|
||||
//
|
||||
// New to Java version 8 are lambda expressions. Lambdas are more commonly found
|
||||
// in functional programming languages, which means they are methods which can
|
||||
// be created without belonging to a class, passed around as if it were itself
|
||||
// an object, and executed on demand.
|
||||
//
|
||||
// Final note, lambdas must implement a functional interface. A functional
|
||||
// interface is one which has only a single abstract method declared. It can
|
||||
// have any number of default methods. Lambda expressions can be used as an
|
||||
// instance of that functional interface. Any interface meeting the requirements
|
||||
// is treated as a functional interface. You can read more about interfaces
|
||||
// above.
|
||||
//
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.function.*;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
public class Lambdas {
|
||||
public static void main(String[] args) {
|
||||
// Lambda declaration syntax:
|
||||
// <zero or more parameters> -> <expression body or statement block>
|
||||
|
||||
// We will use this hashmap in our examples below.
|
||||
Map<String, String> planets = new HashMap<>();
|
||||
planets.put("Mercury", "87.969");
|
||||
planets.put("Venus", "224.7");
|
||||
planets.put("Earth", "365.2564");
|
||||
planets.put("Mars", "687");
|
||||
planets.put("Jupiter", "4,332.59");
|
||||
planets.put("Saturn", "10,759");
|
||||
planets.put("Uranus", "30,688.5");
|
||||
planets.put("Neptune", "60,182");
|
||||
|
||||
// Lambda with zero parameters using the Supplier functional interface
|
||||
// from java.util.function.Supplier. The actual lambda expression is
|
||||
// what comes after numPlanets =.
|
||||
Supplier<String> numPlanets = () -> Integer.toString(planets.size());
|
||||
System.out.format("Number of Planets: %s\n\n", numPlanets.get());
|
||||
|
||||
// Lambda with one parameter and using the Consumer functional interface
|
||||
// from java.util.function.Consumer. This is because planets is a Map,
|
||||
// which implements both Collection and Iterable. The forEach used here,
|
||||
// found in Iterable, applies the lambda expression to each member of
|
||||
// the Collection. The default implementation of forEach behaves as if:
|
||||
/*
|
||||
for (T t : this)
|
||||
action.accept(t);
|
||||
*/
|
||||
|
||||
// The actual lambda expression is the parameter passed to forEach.
|
||||
planets.keySet().forEach((p) -> System.out.format("%s\n", p));
|
||||
|
||||
// If you are only passing a single argument, then the above can also be
|
||||
// written as (note absent parentheses around p):
|
||||
planets.keySet().forEach(p -> System.out.format("%s\n", p));
|
||||
|
||||
// Tracing the above, we see that planets is a HashMap, keySet() returns
|
||||
// a Set of its keys, forEach applies each element as the lambda
|
||||
// expression of: (parameter p) -> System.out.format("%s\n", p). Each
|
||||
// time, the element is said to be "consumed" and the statement(s)
|
||||
// referred to in the lambda body is applied. Remember the lambda body
|
||||
// is what comes after the ->.
|
||||
|
||||
// The above without use of lambdas would look more traditionally like:
|
||||
for (String planet : planets.keySet()) {
|
||||
System.out.format("%s\n", planet);
|
||||
}
|
||||
|
||||
// This example differs from the above in that a different forEach
|
||||
// implementation is used: the forEach found in the HashMap class
|
||||
// implementing the Map interface. This forEach accepts a BiConsumer,
|
||||
// which generically speaking is a fancy way of saying it handles
|
||||
// the Set of each Key -> Value pairs. This default implementation
|
||||
// behaves as if:
|
||||
/*
|
||||
for (Map.Entry<K, V> entry : map.entrySet())
|
||||
action.accept(entry.getKey(), entry.getValue());
|
||||
*/
|
||||
|
||||
// The actual lambda expression is the parameter passed to forEach.
|
||||
String orbits = "%s orbits the Sun in %s Earth days.\n";
|
||||
planets.forEach((K, V) -> System.out.format(orbits, K, V));
|
||||
|
||||
// The above without use of lambdas would look more traditionally like:
|
||||
for (String planet : planets.keySet()) {
|
||||
System.out.format(orbits, planet, planets.get(planet));
|
||||
}
|
||||
|
||||
// Or, if following more closely the specification provided by the
|
||||
// default implementation:
|
||||
for (Map.Entry<String, String> planet : planets.entrySet()) {
|
||||
System.out.format(orbits, planet.getKey(), planet.getValue());
|
||||
}
|
||||
|
||||
// These examples cover only the very basic use of lambdas. It might not
|
||||
// seem like much or even very useful, but remember that a lambda can be
|
||||
// created as an object that can later be passed as parameters to other
|
||||
// methods.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
@ -266,6 +266,15 @@ for (var x in person){
|
||||
description += person[x] + " ";
|
||||
} // description = 'Paul Ken 18 '
|
||||
|
||||
// The for/of statement allows iteration over iterable objects (including the built-in String,
|
||||
// Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set,
|
||||
// and user-defined iterables).
|
||||
var myPets = "";
|
||||
var pets = ["cat", "dog", "hamster", "hedgehog"];
|
||||
for (var pet of pets){
|
||||
myPets += pet + " ";
|
||||
} // myPets = 'cat dog hamster hedgehog '
|
||||
|
||||
// && is logical and, || is logical or
|
||||
if (house.size == "big" && house.colour == "blue"){
|
||||
house.contains = "bear";
|
||||
@ -600,10 +609,6 @@ of the language.
|
||||
[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with
|
||||
attached terminal
|
||||
|
||||
[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great
|
||||
derivative of Eloquent Javascript with extra explanations and clarifications for
|
||||
some of the more complicated examples.
|
||||
|
||||
[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.
|
||||
|
||||
@ -624,6 +629,5 @@ Mozilla Developer Network.
|
||||
[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/
|
||||
[11]: https://javascript.info/
|
||||
|
@ -104,7 +104,7 @@ tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
|
||||
// 3. Manipulation
|
||||
|
||||
// These are similar to effects but can do more
|
||||
$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div
|
||||
$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div
|
||||
|
||||
// Common manipulation methods
|
||||
$('p').append('Hello world'); // Adds to end of element
|
||||
@ -126,3 +126,7 @@ $('p').each(function() {
|
||||
|
||||
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
||||
* [Codecademy - jQuery](https://www.codecademy.com/learn/learn-jquery) A good introduction to jQuery in a "learn by doing it" format.
|
||||
|
@ -81,3 +81,5 @@ Supported data types:
|
||||
## Further Reading
|
||||
|
||||
* [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics.
|
||||
|
||||
* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) A concise introduction to JSON.
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -76,7 +76,7 @@ floor 3.14159 / => 3
|
||||
/ ...getting the absolute value...
|
||||
abs -3.14159 / => 3.14159
|
||||
/ ...and many other things
|
||||
/ see http://code.kx.com/wiki/Reference for more
|
||||
/ see http://code.kx.com/q/ref/card/ for more
|
||||
|
||||
/ q has no operator precedence, everything is evaluated right to left
|
||||
/ so results like this might take some getting used to
|
||||
@ -174,7 +174,7 @@ t - 00:10:00.000 / => 00:50:00.000
|
||||
d.year / => 2015i
|
||||
d.mm / => 12i
|
||||
d.dd / => 25i
|
||||
/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Temporal_Data for more
|
||||
/ see http://code.kx.com/q4m3/2_Basic_Data_Types_Atoms/#25-temporal-data for more
|
||||
|
||||
/ q also has an infinity value so div by zero will not throw an error
|
||||
1%0 / => 0w
|
||||
@ -183,7 +183,7 @@ d.dd / => 25i
|
||||
/ And null types for representing missing values
|
||||
0N / => null int
|
||||
0n / => null float
|
||||
/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Null_Values for more
|
||||
/ see http://code.kx.com/q4m3/2_Basic_Data_Types_Atoms/#27-nulls for more
|
||||
|
||||
/ q has standard control structures
|
||||
/ if is as you might expect (; separates the condition and instructions)
|
||||
@ -642,7 +642,7 @@ kt upsert ([]name:`Thomas`Chester;age:33 58;height:175 179;sex:`f`m)
|
||||
/ => Thomas 32 175 m
|
||||
|
||||
/ Most of the standard SQL joins are present in q-sql, plus a few new friends
|
||||
/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Joins
|
||||
/ see http://code.kx.com/q4m3/9_Queries_q-sql/#99-joins
|
||||
/ the two most important (commonly used) are lj and aj
|
||||
|
||||
/ lj is basically the same as SQL LEFT JOIN
|
||||
@ -669,7 +669,7 @@ aj[`time`sym;trades;quotes]
|
||||
/ => 10:01:04 ge 150
|
||||
/ for each row in the trade table, the last (prevailing) quote (px) for that sym
|
||||
/ is joined on.
|
||||
/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Asof_Join
|
||||
/ see http://code.kx.com/q4m3/9_Queries_q-sql/#998-as-of-joins
|
||||
|
||||
////////////////////////////////////
|
||||
///// Extra/Advanced //////
|
||||
@ -689,14 +689,14 @@ first each (1 2 3;4 5 6;7 8 9)
|
||||
|
||||
/ each-left (\:) and each-right (/:) modify a two-argument function
|
||||
/ to treat one of the arguments and individual variables instead of a list
|
||||
1 2 3 +\: 1 2 3
|
||||
/ => 2 3 4
|
||||
/ => 3 4 5
|
||||
/ => 4 5 6
|
||||
1 2 3 +/: 1 2 3
|
||||
/ => 2 3 4
|
||||
/ => 3 4 5
|
||||
/ => 4 5 6
|
||||
1 2 3 +\: 11 22 33
|
||||
/ => 12 23 34
|
||||
/ => 13 24 35
|
||||
/ => 14 25 36
|
||||
1 2 3 +/: 11 22 33
|
||||
/ => 12 13 14
|
||||
/ => 23 24 25
|
||||
/ => 34 35 36
|
||||
|
||||
/ The true alternatives to loops in q are the adverbs scan (\) and over (/)
|
||||
/ their behaviour differs based on the number of arguments the function they
|
||||
@ -716,7 +716,7 @@ first each (1 2 3;4 5 6;7 8 9)
|
||||
{x + y}/[1 2 3 4 5] / => 15 (only the final result)
|
||||
|
||||
/ There are other adverbs and uses, this is only intended as quick overview
|
||||
/ http://code.kx.com/wiki/JB:QforMortals2/functions#Adverbs
|
||||
/ http://code.kx.com/q4m3/6_Functions/#67-adverbs
|
||||
|
||||
////// Scripts //////
|
||||
/ q scripts can be loaded from a q session using the "\l" command
|
||||
@ -756,7 +756,7 @@ select from splayed / (the columns are read from disk on request)
|
||||
/ => 1 1
|
||||
/ => 2 2
|
||||
/ => 3 3
|
||||
/ see http://code.kx.com/wiki/JB:KdbplusForMortals/contents for more
|
||||
/ see http://code.kx.com/q4m3/14_Introduction_to_Kdb+/ for more
|
||||
|
||||
////// Frameworks //////
|
||||
/ kdb+ is typically used for data capture and analysis.
|
||||
@ -769,8 +769,8 @@ select from splayed / (the columns are read from disk on request)
|
||||
|
||||
## Want to know more?
|
||||
|
||||
* [*q for mortals* q language tutorial](http://code.kx.com/wiki/JB:QforMortals2/contents)
|
||||
* [*kdb for mortals* on disk data tutorial](http://code.kx.com/wiki/JB:KdbplusForMortals/contents)
|
||||
* [q language reference](http://code.kx.com/wiki/Reference)
|
||||
* [*q for mortals* q language tutorial](http://code.kx.com/q4m3/)
|
||||
* [*Introduction to Kdb+* on disk data tutorial](http://code.kx.com/q4m3/14_Introduction_to_Kdb+/)
|
||||
* [q language reference](http://code.kx.com/q/ref/card/)
|
||||
* [Online training courses](http://training.aquaq.co.uk/)
|
||||
* [TorQ production framework](https://github.com/AquaQAnalytics/TorQ)
|
||||
|
@ -25,7 +25,7 @@ lang: ko-kr
|
||||
|
||||
## HTML 요소
|
||||
HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마크다운이라는 것입니다.
|
||||
```markdown
|
||||
```md
|
||||
<!--따라서 주석과 같은 HTML 요소들을 마크다운에 사용할 수 있으며, 마크다운 파서에 영향을
|
||||
받지 않을 것입니다. 하지만 마크다운 파일에서 HTML 요소를 만든다면 그 요소의 안에서는
|
||||
마크다운 문법을 사용할 수 없습니다.-->
|
||||
@ -34,7 +34,7 @@ HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마
|
||||
|
||||
텍스트 앞에 붙이는 우물 정 기호(#)의 갯수에 따라 `<h1>`부터 `<h6>`까지의 HTML 요소를
|
||||
손쉽게 작성할 수 있습니다.
|
||||
```markdown
|
||||
```md
|
||||
# <h1>입니다.
|
||||
## <h2>입니다.
|
||||
### <h3>입니다.
|
||||
@ -43,7 +43,7 @@ HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마
|
||||
###### <h6>입니다.
|
||||
```
|
||||
또한 h1과 h2를 나타내는 다른 방법이 있습니다.
|
||||
```markdown
|
||||
```md
|
||||
h1입니다.
|
||||
=============
|
||||
|
||||
@ -53,7 +53,7 @@ h2입니다.
|
||||
## 간단한 텍스트 꾸미기
|
||||
|
||||
마크다운으로 쉽게 텍스트를 기울이거나 굵게 할 수 있습니다.
|
||||
```markdown
|
||||
```md
|
||||
*기울인 텍스트입니다.*
|
||||
_이 텍스트도 같습니다._
|
||||
|
||||
@ -65,14 +65,14 @@ __이 텍스트도 같습니다.__
|
||||
*__이것도 같습니다.__*
|
||||
```
|
||||
깃헙 전용 마크다운에는 취소선도 있습니다.
|
||||
```markdown
|
||||
```md
|
||||
~~이 텍스트에는 취소선이 그려집니다.~~
|
||||
```
|
||||
## 문단
|
||||
|
||||
문단은 하나 이상의 빈 줄로 구분되는, 한 줄 이상의 인접한 텍스트입니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
문단입니다. 문단에 글을 쓰다니 재밌지 않나요?
|
||||
|
||||
이제 두 번째 문단입니다.
|
||||
@ -83,7 +83,7 @@ __이 텍스트도 같습니다.__
|
||||
HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어쓰기로 문단을 끝내고
|
||||
새 문단을 시작할 수 있습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
띄어쓰기 두 개로 끝나는 문단 (마우스로 긁어 보세요).
|
||||
|
||||
이 위에는 `<br />` 태그가 있습니다.
|
||||
@ -91,7 +91,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
인용문은 > 문자로 쉽게 쓸 수 있습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
> 인용문입니다. 수동으로 개행하고서
|
||||
> 줄마다 `>`를 칠 수도 있고 줄을 길게 쓴 다음에 저절로 개행되게 내버려 둘 수도 있습니다.
|
||||
> `>`로 시작하기만 한다면 차이가 없습니다.
|
||||
@ -103,7 +103,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
## 목록
|
||||
순서가 없는 목록은 별표, 더하기, 하이픈을 이용해 만들 수 있습니다.
|
||||
```markdown
|
||||
```md
|
||||
* 이거
|
||||
* 저거
|
||||
* 그거
|
||||
@ -111,7 +111,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
또는
|
||||
|
||||
```markdown
|
||||
```md
|
||||
+ 이거
|
||||
+ 저거
|
||||
+ 그거
|
||||
@ -119,7 +119,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
또는
|
||||
|
||||
```markdown
|
||||
```md
|
||||
- 이거
|
||||
- 저거
|
||||
- 그거
|
||||
@ -127,7 +127,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
순서가 있는 목록은 숫자와 마침표입니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. 하나
|
||||
2. 둘
|
||||
3. 셋
|
||||
@ -135,7 +135,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
숫자를 정확히 붙이지 않더라도 제대로 된 순서로 보여주겠지만, 좋은 생각은 아닙니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. 하나
|
||||
1. 둘
|
||||
1. 셋
|
||||
@ -144,7 +144,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
목록 안에 목록이 올 수도 있습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. 하나
|
||||
2. 둘
|
||||
3. 셋
|
||||
@ -155,7 +155,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어
|
||||
|
||||
심지어 할 일 목록도 있습니다. HTML 체크박스가 만들어집니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다.
|
||||
- [ ] 첫 번째 할 일
|
||||
- [ ] 두 번째 할 일
|
||||
@ -168,13 +168,13 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다.
|
||||
띄어쓰기 네 개 혹은 탭 한 개로 줄을 들여씀으로서 (`<code> 요소를 사용하여`) 코드를
|
||||
나타낼 수 있습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
puts "Hello, world!"
|
||||
```
|
||||
|
||||
탭을 더 치거나 띄어쓰기를 네 번 더 함으로써 코드를 들여쓸 수 있습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
my_array.each do |item|
|
||||
puts item
|
||||
end
|
||||
@ -182,7 +182,7 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다.
|
||||
|
||||
인라인 코드는 백틱 문자를 이용하여 나타냅니다. `
|
||||
|
||||
```markdown
|
||||
```md
|
||||
철수는 `go_to()` 함수가 뭘 했는지도 몰랐어!
|
||||
```
|
||||
|
||||
@ -202,7 +202,7 @@ end
|
||||
|
||||
수평선(`<hr/>`)은 셋 이상의 별표나 하이픈을 이용해 쉽게 나타낼 수 있습니다.
|
||||
띄어쓰기가 포함될 수 있습니다.
|
||||
```markdown
|
||||
```md
|
||||
***
|
||||
---
|
||||
- - -
|
||||
@ -213,19 +213,19 @@ end
|
||||
마크다운의 장점 중 하나는 링크를 만들기 쉽다는 것입니다. 대괄호 안에 나타낼 텍스트를 쓰고
|
||||
괄호 안에 URL을 쓰면 됩니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[클릭](http://test.com/)
|
||||
```
|
||||
|
||||
괄호 안에 따옴표를 이용해 링크에 제목을 달 수도 있습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[클릭](http://test.com/ "test.com으로 가기")
|
||||
```
|
||||
|
||||
상대 경로도 유효합니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[music으로 가기](/music/).
|
||||
```
|
||||
|
||||
@ -251,7 +251,7 @@ end
|
||||
## 이미지
|
||||
이미지는 링크와 같지만 앞에 느낌표가 붙습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
![이미지의 alt 속성](http://imgur.com/myimage.jpg "제목")
|
||||
```
|
||||
|
||||
@ -264,18 +264,18 @@ end
|
||||
## 기타
|
||||
### 자동 링크
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<http://testwebsite.com/>와
|
||||
[http://testwebsite.com/](http://testwebsite.com/)는 동일합니다.
|
||||
```
|
||||
|
||||
### 이메일 자동 링크
|
||||
```markdown
|
||||
```md
|
||||
<foo@bar.com>
|
||||
```
|
||||
### 탈출 문자
|
||||
|
||||
```markdown
|
||||
```md
|
||||
*별표 사이에 이 텍스트*를 치고 싶지만 기울이고 싶지는 않다면
|
||||
이렇게 하시면 됩니다. \*별표 사이에 이 텍스트\*.
|
||||
```
|
||||
@ -284,7 +284,7 @@ end
|
||||
|
||||
깃헙 전용 마크다운에서는 `<kbd>` 태그를 이용해 키보드 키를 나타낼 수 있습니다.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
컴퓨터가 멈췄다면 눌러보세요.
|
||||
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||
```
|
||||
@ -292,14 +292,14 @@ end
|
||||
### 표
|
||||
|
||||
표는 깃헙 전용 마크다운에서만 쓸 수 있고 다소 복잡하지만, 정말 쓰고 싶으시다면
|
||||
```markdown
|
||||
```md
|
||||
| 1열 | 2열 | 3열 |
|
||||
| :--------| :-------: | --------: |
|
||||
| 왼쪽 정렬 | 가운데 정렬 | 오른쪽 정렬 |
|
||||
| 머시기 | 머시기 | 머시기 |
|
||||
```
|
||||
혹은
|
||||
```markdown
|
||||
```md
|
||||
1열 | 2열 | 3열
|
||||
:-- | :-: | --:
|
||||
으악 너무 못생겼어 | 그만 | 둬
|
||||
|
@ -65,7 +65,7 @@ fun helloWorld(val name : String) {
|
||||
A template expression starts with a dollar sign ($).
|
||||
*/
|
||||
val fooTemplateString = "$fooString has ${fooString.length} characters"
|
||||
println(fooTemplateString) // => My String Is Here! has 18 characters
|
||||
println(fooTemplateString) // => My String Is Here! has 18 characters
|
||||
|
||||
/*
|
||||
For a variable to hold null it must be explicitly specified as nullable.
|
||||
@ -175,12 +175,12 @@ fun helloWorld(val name : String) {
|
||||
// Objects can be destructured into multiple variables.
|
||||
val (a, b, c) = fooCopy
|
||||
println("$a $b $c") // => 1 100 4
|
||||
|
||||
|
||||
// destructuring in "for" loop
|
||||
for ((a, b, c) in listOf(fooData)) {
|
||||
println("$a $b $c") // => 1 100 4
|
||||
}
|
||||
|
||||
|
||||
val mapData = mapOf("a" to 1, "b" to 2)
|
||||
// Map.Entry is destructurable as well
|
||||
for ((key, value) in mapData) {
|
||||
@ -347,6 +347,8 @@ fun helloWorld(val name : String) {
|
||||
|
||||
println(EnumExample.A) // => A
|
||||
println(ObjectExample.hello()) // => hello
|
||||
|
||||
testOperator()
|
||||
}
|
||||
|
||||
// Enum classes are similar to Java enum types.
|
||||
@ -370,6 +372,77 @@ fun useObject() {
|
||||
val someRef: Any = ObjectExample // we use objects name just as is
|
||||
}
|
||||
|
||||
|
||||
/* The not-null assertion operator (!!) converts any value to a non-null type and
|
||||
throws an exception if the value is null.
|
||||
*/
|
||||
var b: String? = "abc"
|
||||
val l = b!!.length
|
||||
|
||||
/* You can add many custom operations using symbol like +, to particular instance
|
||||
by overloading the built-in kotlin operator, using "operator" keyword
|
||||
|
||||
below is the sample class to add some operator, and the most basic example
|
||||
*/
|
||||
data class SomeClass(var savedValue: Int = 0)
|
||||
|
||||
// instance += valueToAdd
|
||||
operator fun SomeClass.plusAssign(valueToAdd: Int) {
|
||||
this.savedValue += valueToAdd
|
||||
}
|
||||
|
||||
// -instance
|
||||
operator fun SomeClass.unaryMinus() = SomeClass(-this.savedValue)
|
||||
|
||||
// ++instance or instance++
|
||||
operator fun SomeClass.inc() = SomeClass(this.savedValue + 1)
|
||||
|
||||
// instance * other
|
||||
operator fun SomeClass.times(other: SomeClass) =
|
||||
SomeClass(this.savedValue * other.savedValue)
|
||||
|
||||
// an overload for multiply
|
||||
operator fun SomeClass.times(value: Int) = SomeClass(this.savedValue * value)
|
||||
|
||||
// other in instance
|
||||
operator fun SomeClass.contains(other: SomeClass) =
|
||||
other.savedValue == this.savedValue
|
||||
|
||||
// instance[dummyIndex] = valueToSet
|
||||
operator fun SomeClass.set(dummyIndex: Int, valueToSet: Int) {
|
||||
this.savedValue = valueToSet + dummyIndex
|
||||
}
|
||||
|
||||
// instance()
|
||||
operator fun SomeClass.invoke() {
|
||||
println("instance invoked by invoker")
|
||||
}
|
||||
|
||||
/* return type must be Integer,
|
||||
so that, it can be translated to "returned value" compareTo 0
|
||||
|
||||
for equality (==,!=) using operator will violates overloading equals function,
|
||||
since it is already defined in Any class
|
||||
*/
|
||||
operator fun SomeClass.compareTo(other: SomeClass) =
|
||||
this.savedValue - other.savedValue
|
||||
|
||||
fun testOperator() {
|
||||
var x = SomeClass(4)
|
||||
|
||||
println(x) // => "SomeClass(savedValue=4)"
|
||||
x += 10
|
||||
println(x) // => "SomeClass(savedValue=14)"
|
||||
println(-x) // => "SomeClass(savedValue=-14)"
|
||||
println(++x) // => "SomeClass(savedValue=15)"
|
||||
println(x * SomeClass(3)) // => "SomeClass(savedValue=45)"
|
||||
println(x * 2) // => "SomeClass(savedValue=30)"
|
||||
println(SomeClass(15) in x) // => true
|
||||
x[2] = 10
|
||||
println(x) // => "SomeClass(savedValue=12)"
|
||||
x() // => "instance invoked by invoker"
|
||||
println(x >= 15) // => false
|
||||
}
|
||||
```
|
||||
|
||||
### Further Reading
|
||||
|
214
lambda-calculus.html.markdown
Normal file
214
lambda-calculus.html.markdown
Normal file
@ -0,0 +1,214 @@
|
||||
---
|
||||
category: Algorithms & Data Structures
|
||||
name: Lambda Calculus
|
||||
contributors:
|
||||
- ["Max Sun", "http://github.com/maxsun"]
|
||||
- ["Yan Hui Hang", "http://github.com/yanhh0"]
|
||||
---
|
||||
|
||||
# Lambda Calculus
|
||||
|
||||
Lambda calculus (λ-calculus), originally created by
|
||||
[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church),
|
||||
is the world's smallest programming language.
|
||||
Despite not having numbers, strings, booleans, or any non-function datatype,
|
||||
lambda calculus can be used to represent any Turing Machine!
|
||||
|
||||
Lambda calculus is composed of 3 elements: **variables**, **functions**, and
|
||||
**applications**.
|
||||
|
||||
|
||||
| Name | Syntax | Example | Explanation |
|
||||
|-------------|------------------------------------|-----------|-----------------------------------------------|
|
||||
| Variable | `<name>` | `x` | a variable named "x" |
|
||||
| Function | `λ<parameters>.<body>` | `λx.x` | a function with parameter "x" and body "x" |
|
||||
| Application | `<function><variable or function>` | `(λx.x)a` | calling the function "λx.x" with argument "a" |
|
||||
|
||||
The most basic function is the identity function: `λx.x` which is equivalent to
|
||||
`f(x) = x`. The first "x" is the function's argument, and the second is the
|
||||
body of the function.
|
||||
|
||||
## Free vs. Bound Variables:
|
||||
|
||||
- In the function `λx.x`, "x" is called a bound variable because it is both in
|
||||
the body of the function and a parameter.
|
||||
- In `λx.y`, "y" is called a free variable because it is never declared before hand.
|
||||
|
||||
## Evaluation:
|
||||
|
||||
Evaluation is done via
|
||||
[β-Reduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction),
|
||||
which is essentially lexically-scoped substitution.
|
||||
|
||||
When evaluating the
|
||||
expression `(λx.x)a`, we replace all occurences of "x" in the function's body
|
||||
with "a".
|
||||
|
||||
- `(λx.x)a` evaluates to: `a`
|
||||
- `(λx.y)a` evaluates to: `y`
|
||||
|
||||
You can even create higher-order functions:
|
||||
|
||||
- `(λx.(λy.x))a` evaluates to: `λy.a`
|
||||
|
||||
Although lambda calculus traditionally supports only single parameter
|
||||
functions, we can create multi-parameter functions using a technique called
|
||||
[currying](https://en.wikipedia.org/wiki/Currying).
|
||||
|
||||
- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = ((x y) z)`
|
||||
|
||||
Sometimes `λxy.<body>` is used interchangeably with: `λx.λy.<body>`
|
||||
|
||||
----
|
||||
|
||||
It's important to recognize that traditional **lambda calculus doesn't have
|
||||
numbers, characters, or any non-function datatype!**
|
||||
|
||||
## Boolean Logic:
|
||||
|
||||
There is no "True" or "False" in lambda calculus. There isn't even a 1 or 0.
|
||||
|
||||
Instead:
|
||||
|
||||
`T` is represented by: `λx.λy.x`
|
||||
|
||||
`F` is represented by: `λx.λy.y`
|
||||
|
||||
First, we can define an "if" function `λbtf` that
|
||||
returns `t` if `b` is True and `f` if `b` is False
|
||||
|
||||
`IF` is equivalent to: `λb.λt.λf.b t f`
|
||||
|
||||
Using `IF`, we can define the basic boolean logic operators:
|
||||
|
||||
`a AND b` is equivalent to: `λab.IF a b F`
|
||||
|
||||
`a OR b` is equivalent to: `λab.IF a T b`
|
||||
|
||||
`a NOT b` is equivalent to: `λa.IF a F T`
|
||||
|
||||
*Note: `IF a b c` is essentially saying: `IF((a b) c)`*
|
||||
|
||||
## Numbers:
|
||||
|
||||
Although there are no numbers in lambda calculus, we can encode numbers using
|
||||
[Church numerals](https://en.wikipedia.org/wiki/Church_encoding).
|
||||
|
||||
For any number n: <code>n = λf.f<sup>n</sup></code> so:
|
||||
|
||||
`0 = λf.λx.x`
|
||||
|
||||
`1 = λf.λx.f x`
|
||||
|
||||
`2 = λf.λx.f(f x)`
|
||||
|
||||
`3 = λf.λx.f(f(f x))`
|
||||
|
||||
To increment a Church numeral,
|
||||
we use the successor function `S(n) = n + 1` which is:
|
||||
|
||||
`S = λn.λf.λx.f((n f) x)`
|
||||
|
||||
Using successor, we can define add:
|
||||
|
||||
`ADD = λab.(a S)n`
|
||||
|
||||
**Challenge:** try defining your own multiplication function!
|
||||
|
||||
## Get even smaller: SKI, SK and Iota
|
||||
|
||||
### SKI Combinator Calculus
|
||||
|
||||
Let S, K, I be the following functions:
|
||||
|
||||
`I x = x`
|
||||
|
||||
`K x y = x`
|
||||
|
||||
`S x y z = x z (y z)`
|
||||
|
||||
We can convert an expression in the lambda calculus to an expression
|
||||
in the SKI combinator calculus:
|
||||
|
||||
1. `λx.x = I`
|
||||
2. `λx.c = Kc`
|
||||
3. `λx.(y z) = S (λx.y) (λx.z)`
|
||||
|
||||
Take the church number 2 for example:
|
||||
|
||||
`2 = λf.λx.f(f x)`
|
||||
|
||||
For the inner part `λx.f(f x)`:
|
||||
```
|
||||
λx.f(f x)
|
||||
= S (λx.f) (λx.(f x)) (case 3)
|
||||
= S (K f) (S (λx.f) (λx.x)) (case 2, 3)
|
||||
= S (K f) (S (K f) I) (case 2, 1)
|
||||
```
|
||||
|
||||
So:
|
||||
```
|
||||
2
|
||||
= λf.λx.f(f x)
|
||||
= λf.(S (K f) (S (K f) I))
|
||||
= λf.((S (K f)) (S (K f) I))
|
||||
= S (λf.(S (K f))) (λf.(S (K f) I)) (case 3)
|
||||
```
|
||||
|
||||
For the first argument `λf.(S (K f))`:
|
||||
```
|
||||
λf.(S (K f))
|
||||
= S (λf.S) (λf.(K f)) (case 3)
|
||||
= S (K S) (S (λf.K) (λf.f)) (case 2, 3)
|
||||
= S (K S) (S (K K) I) (case 2, 3)
|
||||
```
|
||||
|
||||
For the second argument `λf.(S (K f) I)`:
|
||||
```
|
||||
λf.(S (K f) I)
|
||||
= λf.((S (K f)) I)
|
||||
= S (λf.(S (K f))) (λf.I) (case 3)
|
||||
= S (S (λf.S) (λf.(K f))) (K I) (case 2, 3)
|
||||
= S (S (K S) (S (λf.K) (λf.f))) (K I) (case 1, 3)
|
||||
= S (S (K S) (S (K K) I)) (K I) (case 1, 2)
|
||||
```
|
||||
|
||||
Merging them up:
|
||||
```
|
||||
2
|
||||
= S (λf.(S (K f))) (λf.(S (K f) I))
|
||||
= S (S (K S) (S (K K) I)) (S (S (K S) (S (K K) I)) (K I))
|
||||
```
|
||||
|
||||
Expanding this, we would end up with the same expression for the
|
||||
church number 2 again.
|
||||
|
||||
### SK Combinator Calculus
|
||||
|
||||
The SKI combinator calculus can still be reduced further. We can
|
||||
remove the I combinator by noting that `I = SKK`. We can substitute
|
||||
all `I`'s with `SKK`.
|
||||
|
||||
### Iota Combinator
|
||||
|
||||
The SK combinator calculus is still not minimal. Defining:
|
||||
|
||||
```
|
||||
ι = λf.((f S) K)
|
||||
```
|
||||
|
||||
We have:
|
||||
|
||||
```
|
||||
I = ιι
|
||||
K = ι(ιI) = ι(ι(ιι))
|
||||
S = ι(K) = ι(ι(ι(ιι)))
|
||||
```
|
||||
|
||||
## For more advanced reading:
|
||||
|
||||
1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf)
|
||||
2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html)
|
||||
3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus)
|
||||
4. [Wikipedia - SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus)
|
||||
5. [Wikipedia - Iota and Jot](https://en.wikipedia.org/wiki/Iota_and_Jot)
|
@ -26,8 +26,8 @@ filename: learn-latex.tex
|
||||
|
||||
% Next we define the packages the document uses.
|
||||
% If you want to include graphics, colored text, or
|
||||
% source code from another language file into your document,
|
||||
% you need to enhance the capabilities of LaTeX. This is done by adding packages.
|
||||
% source code from another language file into your document,
|
||||
% you need to enhance the capabilities of LaTeX. This is done by adding packages.
|
||||
% I'm going to include the float and caption packages for figures
|
||||
% and hyperref package for hyperlinks
|
||||
\usepackage{caption}
|
||||
@ -42,14 +42,14 @@ Svetlana Golubeva}
|
||||
|
||||
% Now we're ready to begin the document
|
||||
% Everything before this line is called "The Preamble"
|
||||
\begin{document}
|
||||
% if we set the author, date, title fields, we can have LaTeX
|
||||
\begin{document}
|
||||
% if we set the author, date, title fields, we can have LaTeX
|
||||
% create a title page for us.
|
||||
\maketitle
|
||||
|
||||
% If we have sections, we can create table of contents. We have to compile our
|
||||
% document twice to make it appear in right order.
|
||||
% It is a good practice to separate the table of contents form the body of the
|
||||
% It is a good practice to separate the table of contents form the body of the
|
||||
% document. To do so we use \newpage command
|
||||
\newpage
|
||||
\tableofcontents
|
||||
@ -58,14 +58,14 @@ Svetlana Golubeva}
|
||||
|
||||
% Most research papers have abstract, you can use the predefined commands for this.
|
||||
% This should appear in its logical order, therefore, after the top matter,
|
||||
% but before the main sections of the body.
|
||||
% but before the main sections of the body.
|
||||
% This command is available in the document classes article and report.
|
||||
\begin{abstract}
|
||||
\LaTeX \hspace{1pt} documentation written as \LaTeX! How novel and totally not
|
||||
my idea!
|
||||
\end{abstract}
|
||||
|
||||
% Section commands are intuitive.
|
||||
% Section commands are intuitive.
|
||||
% All the titles of the sections are added automatically to the table of contents.
|
||||
\section{Introduction}
|
||||
Hello, my name is Colton and together we're going to explore \LaTeX!
|
||||
@ -81,16 +81,16 @@ Much better now.
|
||||
\label{subsec:pythagoras}
|
||||
|
||||
% By using the asterisk we can suppress LaTeX's inbuilt numbering.
|
||||
% This works for other LaTeX commands as well.
|
||||
\section*{This is an unnumbered section}
|
||||
% This works for other LaTeX commands as well.
|
||||
\section*{This is an unnumbered section}
|
||||
However not all sections have to be numbered!
|
||||
|
||||
\section{Some Text notes}
|
||||
%\section{Spacing} % Need to add more information about space intervals
|
||||
\LaTeX \hspace{1pt} is generally pretty good about placing text where it should
|
||||
go. If
|
||||
a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash
|
||||
\hspace{1pt} to the source code. \\
|
||||
go. If
|
||||
a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash
|
||||
\hspace{1pt} to the source code. \\
|
||||
|
||||
\section{Lists}
|
||||
Lists are one of the easiest things to create in \LaTeX! I need to go shopping
|
||||
@ -110,7 +110,7 @@ tomorrow, so let's make a grocery list.
|
||||
\section{Math}
|
||||
|
||||
One of the primary uses for \LaTeX \hspace{1pt} is to produce academic articles
|
||||
or technical papers. Usually in the realm of math and science. As such,
|
||||
or technical papers. Usually in the realm of math and science. As such,
|
||||
we need to be able to add special symbols to our paper! \\
|
||||
|
||||
Math has many symbols, far beyond what you can find on a keyboard;
|
||||
@ -118,9 +118,9 @@ Set and relation symbols, arrows, operators, and Greek letters to name a few.\\
|
||||
|
||||
Sets and relations play a vital role in many mathematical research papers.
|
||||
Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\
|
||||
% Notice how I needed to add $ signs before and after the symbols. This is
|
||||
% because when writing, we are in text-mode.
|
||||
% However, the math symbols only exist in math-mode.
|
||||
% Notice how I needed to add $ signs before and after the symbols. This is
|
||||
% because when writing, we are in text-mode.
|
||||
% However, the math symbols only exist in math-mode.
|
||||
% We can enter math-mode from text mode with the $ signs.
|
||||
% The opposite also holds true. Variable can also be rendered in math-mode.
|
||||
% We can also enter math mode with \[\]
|
||||
@ -131,12 +131,12 @@ My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
|
||||
I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know
|
||||
about! \\
|
||||
|
||||
Operators are essential parts of a mathematical document:
|
||||
trigonometric functions ($\sin$, $\cos$, $\tan$),
|
||||
logarithms and exponentials ($\log$, $\exp$),
|
||||
limits ($\lim$), etc.
|
||||
have per-defined LaTeX commands.
|
||||
Let's write an equation to see how it's done:
|
||||
Operators are essential parts of a mathematical document:
|
||||
trigonometric functions ($\sin$, $\cos$, $\tan$),
|
||||
logarithms and exponentials ($\log$, $\exp$),
|
||||
limits ($\lim$), etc.
|
||||
have per-defined LaTeX commands.
|
||||
Let's write an equation to see how it's done:
|
||||
$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\
|
||||
|
||||
Fractions (Numerator-denominators) can be written in these forms:
|
||||
@ -156,31 +156,31 @@ We can also insert equations in an ``equation environment''.
|
||||
\label{eq:pythagoras} % for referencing
|
||||
\end{equation} % all \begin statements must have an end statement
|
||||
|
||||
We can then reference our new equation!
|
||||
We can then reference our new equation!
|
||||
Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also
|
||||
the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled:
|
||||
the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled:
|
||||
figures, equations, sections, etc.
|
||||
|
||||
Summations and Integrals are written with sum and int commands:
|
||||
|
||||
% Some LaTeX compilers will complain if there are blank lines
|
||||
% In an equation environment.
|
||||
\begin{equation}
|
||||
\begin{equation}
|
||||
\sum_{i=0}^{5} f_{i}
|
||||
\end{equation}
|
||||
\begin{equation}
|
||||
\end{equation}
|
||||
\begin{equation}
|
||||
\int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
|
||||
\end{equation}
|
||||
\end{equation}
|
||||
|
||||
\section{Figures}
|
||||
|
||||
Let's insert a Figure. Figure placement can get a little tricky.
|
||||
Let's insert a Figure. Figure placement can get a little tricky.
|
||||
I definitely have to lookup the placement options each time.
|
||||
|
||||
\begin{figure}[H] % H here denoted the placement option.
|
||||
\begin{figure}[H] % H here denoted the placement option.
|
||||
\centering % centers the figure on the page
|
||||
% Inserts a figure scaled to 0.8 the width of the page.
|
||||
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
|
||||
%\includegraphics[width=0.8\linewidth]{right-triangle.png}
|
||||
% Commented out for compilation purposes. Please use your imagination.
|
||||
\caption{Right triangle with sides $a$, $b$, $c$}
|
||||
\label{fig:right-triangle}
|
||||
@ -193,7 +193,7 @@ We can also insert Tables in the same way as figures.
|
||||
\caption{Caption for the Table.}
|
||||
% the {} arguments below describe how each row of the table is drawn.
|
||||
% Again, I have to look these up. Each. And. Every. Time.
|
||||
\begin{tabular}{c|cc}
|
||||
\begin{tabular}{c|cc}
|
||||
Number & Last Name & First Name \\ % Column rows are separated by &
|
||||
\hline % a horizontal line
|
||||
1 & Biggus & Dickus \\
|
||||
@ -204,34 +204,34 @@ We can also insert Tables in the same way as figures.
|
||||
\section{Getting \LaTeX \hspace{1pt} to not compile something (i.e. Source Code)}
|
||||
Let's say we want to include some code into our \LaTeX \hspace{1pt} document,
|
||||
we would then need \LaTeX \hspace{1pt} to not try and interpret that text and
|
||||
instead just print it to the document. We do this with a verbatim
|
||||
environment.
|
||||
instead just print it to the document. We do this with a verbatim
|
||||
environment.
|
||||
|
||||
% There are other packages that exist (i.e. minty, lstlisting, etc.)
|
||||
% but verbatim is the bare-bones basic one.
|
||||
\begin{verbatim}
|
||||
\begin{verbatim}
|
||||
print("Hello World!")
|
||||
a%b; % look! We can use % signs in verbatim.
|
||||
a%b; % look! We can use % signs in verbatim.
|
||||
random = 4; #decided by fair random dice roll
|
||||
\end{verbatim}
|
||||
|
||||
\section{Compiling}
|
||||
\section{Compiling}
|
||||
|
||||
By now you're probably wondering how to compile this fabulous document
|
||||
By now you're probably wondering how to compile this fabulous document
|
||||
and look at the glorious glory that is a \LaTeX \hspace{1pt} pdf.
|
||||
(yes, this document actually does compile). \\
|
||||
Getting to the final document using \LaTeX \hspace{1pt} consists of the following
|
||||
Getting to the final document using \LaTeX \hspace{1pt} consists of the following
|
||||
steps:
|
||||
\begin{enumerate}
|
||||
\item Write the document in plain text (the ``source code'').
|
||||
\item Compile source code to produce a pdf.
|
||||
\item Compile source code to produce a pdf.
|
||||
The compilation step looks like this (in Linux): \\
|
||||
\begin{verbatim}
|
||||
\begin{verbatim}
|
||||
> pdflatex learn-latex.tex
|
||||
\end{verbatim}
|
||||
\end{enumerate}
|
||||
|
||||
A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the
|
||||
A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the
|
||||
same piece of software. So, you get to see Step 1, but not Step 2 completely.
|
||||
Step 2 is still happening behind the scenes\footnote{In cases, where you use
|
||||
references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2
|
||||
@ -245,17 +245,17 @@ format you defined in Step 1.
|
||||
\section{Hyperlinks}
|
||||
We can also insert hyperlinks in our document. To do so we need to include the
|
||||
package hyperref into preamble with the command:
|
||||
\begin{verbatim}
|
||||
\begin{verbatim}
|
||||
\usepackage{hyperref}
|
||||
\end{verbatim}
|
||||
|
||||
There exists two main types of links: visible URL \\
|
||||
\url{https://learnxinyminutes.com/docs/latex/}, or
|
||||
\url{https://learnxinyminutes.com/docs/latex/}, or
|
||||
\href{https://learnxinyminutes.com/docs/latex/}{shadowed by text}
|
||||
% You can not add extra-spaces or special symbols into shadowing text since it
|
||||
% You can not add extra-spaces or special symbols into shadowing text since it
|
||||
% will cause mistakes during the compilation
|
||||
|
||||
This package also produces list of tumbnails in the output pdf document and
|
||||
This package also produces list of thumbnails in the output pdf document and
|
||||
active links in the table of contents.
|
||||
|
||||
\section{End}
|
||||
@ -267,7 +267,7 @@ That's all for now!
|
||||
\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 \hspace{1pt} wikibook: {\em
|
||||
\bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em
|
||||
https://en.wikibooks.org/wiki/LaTeX}
|
||||
\bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
|
||||
\end{thebibliography}
|
||||
@ -280,3 +280,4 @@ https://en.wikibooks.org/wiki/LaTeX}
|
||||
|
||||
* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
|
||||
* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
|
||||
* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes)
|
||||
|
@ -62,6 +62,11 @@ if not aBoolValue then print('twas false') end
|
||||
-- in C/js:
|
||||
ans = aBoolValue and 'yes' or 'no' --> 'no'
|
||||
|
||||
-- BEWARE: this only acts as a ternary if the value returned when the condition
|
||||
-- evaluates to true is not `false` or Nil
|
||||
iAmNotFalse = (not aBoolValue) and false or true --> true
|
||||
iAmAlsoNotFalse = (not aBoolValue) and true or false --> true
|
||||
|
||||
karlSum = 0
|
||||
for i = 1, 100 do -- The range includes both ends.
|
||||
karlSum = karlSum + i
|
||||
|
@ -2,6 +2,7 @@
|
||||
language: make
|
||||
contributors:
|
||||
- ["Robert Steed", "https://github.com/robochat"]
|
||||
- ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
|
||||
filename: Makefile
|
||||
---
|
||||
|
||||
@ -11,7 +12,7 @@ target to the most recent version of the source. Famously written over a
|
||||
weekend by Stuart Feldman in 1976, it is still widely used (particularly
|
||||
on Unix and Linux) despite many competitors and criticisms.
|
||||
|
||||
There are many varieties of make in existence, however this article
|
||||
There are many varieties of make in existence, however this article
|
||||
assumes that we are using GNU make which is the standard on Linux.
|
||||
|
||||
```make
|
||||
@ -168,9 +169,9 @@ echo: name2 = Sara # True within the matching rule
|
||||
# Some variables defined automatically by make.
|
||||
echo_inbuilt:
|
||||
echo $(CC)
|
||||
echo ${CXX)}
|
||||
echo ${CXX}
|
||||
echo $(FC)
|
||||
echo ${CFLAGS)}
|
||||
echo ${CFLAGS}
|
||||
echo $(CPPFLAGS)
|
||||
echo ${CXXFLAGS}
|
||||
echo $(LDFLAGS)
|
||||
|
@ -29,7 +29,7 @@ specific to a certain parser.
|
||||
## HTML Elements
|
||||
Markdown is a superset of HTML, so any HTML file is valid Markdown.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<!--This means we can use HTML elements in Markdown, such as the comment
|
||||
element, and they won't be affected by a markdown parser. However, if you
|
||||
create an HTML element in your markdown file, you cannot use markdown syntax
|
||||
@ -41,7 +41,7 @@ within that element's contents.-->
|
||||
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 (#).
|
||||
|
||||
```markdown
|
||||
```md
|
||||
# This is an <h1>
|
||||
## This is an <h2>
|
||||
### This is an <h3>
|
||||
@ -51,7 +51,7 @@ text you want to be in that element by a number of hashes (#).
|
||||
```
|
||||
Markdown also provides us with two alternative ways of indicating h1 and h2.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
This is an h1
|
||||
=============
|
||||
|
||||
@ -63,7 +63,7 @@ This is an h2
|
||||
|
||||
Text can be easily styled as italic or bold using markdown.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
*This text is in italics.*
|
||||
_And so is this text._
|
||||
|
||||
@ -78,7 +78,7 @@ __And so is this text.__
|
||||
In GitHub Flavored Markdown, which is used to render markdown files on
|
||||
GitHub, we also have strikethrough:
|
||||
|
||||
```markdown
|
||||
```md
|
||||
~~This text is rendered with strikethrough.~~
|
||||
```
|
||||
## Paragraphs
|
||||
@ -86,7 +86,7 @@ GitHub, we also have strikethrough:
|
||||
Paragraphs are a one or multiple adjacent lines of text separated by one or
|
||||
multiple blank lines.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
This is a paragraph. I'm typing in a paragraph isn't this fun?
|
||||
|
||||
Now I'm in paragraph 2.
|
||||
@ -99,7 +99,7 @@ I'm in paragraph three!
|
||||
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.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
I end with two spaces (highlight me to see them).
|
||||
|
||||
There's a <br /> above me!
|
||||
@ -107,7 +107,7 @@ There's a <br /> above me!
|
||||
|
||||
Block quotes are easy and done with the > character.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
> 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.
|
||||
> It doesn't make a difference so long as they start with a `>`.
|
||||
@ -121,7 +121,7 @@ Block quotes are easy and done with the > character.
|
||||
## Lists
|
||||
Unordered lists can be made using asterisks, pluses, or hyphens.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
* Item
|
||||
* Item
|
||||
* Another item
|
||||
@ -141,7 +141,7 @@ or
|
||||
|
||||
Ordered lists are done with a number followed by a period.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. Item one
|
||||
2. Item two
|
||||
3. Item three
|
||||
@ -150,7 +150,7 @@ Ordered lists are done with a number followed by a period.
|
||||
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.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. Item one
|
||||
1. Item two
|
||||
1. Item three
|
||||
@ -159,7 +159,7 @@ render the numbers in order, but this may not be a good idea.
|
||||
|
||||
You can also use sublists
|
||||
|
||||
```markdown
|
||||
```md
|
||||
1. Item one
|
||||
2. Item two
|
||||
3. Item three
|
||||
@ -170,7 +170,7 @@ You can also use sublists
|
||||
|
||||
There are even task lists. This creates HTML checkboxes.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Boxes below without the 'x' are unchecked HTML checkboxes.
|
||||
- [ ] First task to complete.
|
||||
- [ ] Second task that needs done
|
||||
@ -183,7 +183,7 @@ This checkbox below will be a checked HTML checkbox.
|
||||
You can indicate a code block (which uses the `<code>` element) by indenting
|
||||
a line with four spaces or a tab.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
This is code
|
||||
So is this
|
||||
```
|
||||
@ -191,15 +191,15 @@ a line with four spaces or a tab.
|
||||
You can also re-tab (or add an additional four spaces) for indentation
|
||||
inside your code
|
||||
|
||||
```markdown
|
||||
```md
|
||||
my_array.each do |item|
|
||||
puts item
|
||||
end
|
||||
```
|
||||
|
||||
Inline code can be created using the backtick character `
|
||||
Inline code can be created using the backtick character `` ` ``
|
||||
|
||||
```markdown
|
||||
```md
|
||||
John didn't even know what the `go_to()` function did!
|
||||
```
|
||||
|
||||
@ -220,7 +220,7 @@ highlighting of the language you specify after the \`\`\`
|
||||
Horizontal rules (`<hr/>`) are easily added with three or more asterisks or
|
||||
hyphens, with or without spaces.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
***
|
||||
---
|
||||
- - -
|
||||
@ -232,17 +232,17 @@ hyphens, with or without spaces.
|
||||
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
|
||||
```md
|
||||
[Click me!](http://test.com/)
|
||||
```
|
||||
You can also add a link title using quotes inside the parentheses.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[Click me!](http://test.com/ "Link to Test.com")
|
||||
```
|
||||
Relative paths work too.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
[Go to music](/music/).
|
||||
```
|
||||
|
||||
@ -269,7 +269,7 @@ But it's not that commonly used.
|
||||
## Images
|
||||
Images are done the same way as links but with an exclamation point in front!
|
||||
|
||||
```markdown
|
||||
```md
|
||||
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
|
||||
```
|
||||
|
||||
@ -281,20 +281,20 @@ And reference style works as expected.
|
||||
## Miscellany
|
||||
### Auto-links
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<http://testwebsite.com/> is equivalent to
|
||||
[http://testwebsite.com/](http://testwebsite.com/)
|
||||
```
|
||||
|
||||
### Auto-links for emails
|
||||
|
||||
```markdown
|
||||
```md
|
||||
<foo@bar.com>
|
||||
```
|
||||
|
||||
### Escaping characters
|
||||
|
||||
```markdown
|
||||
```md
|
||||
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\*.
|
||||
```
|
||||
@ -304,7 +304,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*.
|
||||
In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard
|
||||
keys.
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Your computer crashed? Try sending a
|
||||
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
|
||||
```
|
||||
@ -313,7 +313,7 @@ Your computer crashed? Try sending a
|
||||
Tables are only available in GitHub Flavored Markdown and are slightly
|
||||
cumbersome, but if you really want it:
|
||||
|
||||
```markdown
|
||||
```md
|
||||
| Col1 | Col2 | Col3 |
|
||||
| :----------- | :------: | ------------: |
|
||||
| Left-aligned | Centered | Right-aligned |
|
||||
@ -321,7 +321,7 @@ cumbersome, but if you really want it:
|
||||
```
|
||||
or, for the same results
|
||||
|
||||
```markdown
|
||||
```md
|
||||
Col 1 | Col2 | Col3
|
||||
:-- | :-: | --:
|
||||
Ugh this is so ugly | make it | stop
|
||||
|
@ -221,11 +221,11 @@ A(1, :) =[] % Delete the first row of the matrix
|
||||
A(:, 1) =[] % Delete the first column of the matrix
|
||||
|
||||
transpose(A) % Transpose the matrix, which is the same as:
|
||||
A one
|
||||
ctranspose(A) % Hermitian transpose the matrix
|
||||
% (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)
|
||||
ctranspose(A) % Hermitian transpose the matrix, which is the same as:
|
||||
A' % Concise version of complex transpose
|
||||
% (the transpose, followed by taking complex conjugate of each element)
|
||||
|
||||
|
||||
|
||||
|
||||
@ -374,8 +374,8 @@ disp('Hello World') % Print out a string
|
||||
fprintf % Print to Command Window with more control
|
||||
|
||||
% Conditional statements (the parentheses are optional, but good style)
|
||||
if (a > 15)
|
||||
disp('Greater than 15')
|
||||
if (a > 23)
|
||||
disp('Greater than 23')
|
||||
elseif (a == 23)
|
||||
disp('a is 23')
|
||||
else
|
||||
@ -545,7 +545,7 @@ ans = multiplyLatBy(a,3)
|
||||
|
||||
% The method can also be called using dot notation. In this case, the object
|
||||
% does not need to be passed to the method.
|
||||
ans = a.multiplyLatBy(a,1/3)
|
||||
ans = a.multiplyLatBy(1/3)
|
||||
|
||||
% Matlab functions can be overloaded to handle objects.
|
||||
% In the method above, we have overloaded how Matlab handles
|
||||
|
366
mips.html.markdown
Normal file
366
mips.html.markdown
Normal file
@ -0,0 +1,366 @@
|
||||
---
|
||||
language: "MIPS Assembly"
|
||||
filename: MIPS.asm
|
||||
contributors:
|
||||
- ["Stanley Lim", "https://github.com/Spiderpig86"]
|
||||
---
|
||||
|
||||
The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language
|
||||
is designed to work with the MIPS microprocessor paradigm designed by J. L.
|
||||
Hennessy in 1981. These RISC processors are used in embedded systems such as
|
||||
gateways and routers.
|
||||
|
||||
[Read More](https://en.wikipedia.org/wiki/MIPS_architecture)
|
||||
|
||||
```asm
|
||||
# Comments are denoted with a '#'
|
||||
|
||||
# Everything that occurs after a '#' will be ignored by the assembler's lexer.
|
||||
|
||||
# Programs typically contain a .data and .text sections
|
||||
|
||||
.data # Section where data is stored in memory (allocated in RAM), similar to
|
||||
# variables in higher level languages
|
||||
|
||||
# Declarations follow a ( label: .type value(s) ) form of declaration
|
||||
hello_world: .asciiz "Hello World\n" # Declare a null terminated string
|
||||
num1: .word 42 # Integers are referred to as words
|
||||
# (32 bit value)
|
||||
|
||||
arr1: .word 1, 2, 3, 4, 5 # Array of words
|
||||
arr2: .byte 'a', 'b' # Array of chars (1 byte each)
|
||||
buffer: .space 60 # Allocates space in the RAM
|
||||
# (not cleared to 0)
|
||||
|
||||
# Datatype sizes
|
||||
_byte: .byte 'a' # 1 byte
|
||||
_halfword: .half 53 # 2 bytes
|
||||
_word: .word 3 # 4 bytes
|
||||
_float: .float 3.14 # 4 bytes
|
||||
_double: .double 7.0 # 8 bytes
|
||||
|
||||
.align 2 # Memory alignment of data, where
|
||||
# number indicates byte alignment in
|
||||
# powers of 2. (.align 2 represents
|
||||
# word alignment since 2^2 = 4 bytes)
|
||||
|
||||
.text # Section that contains instructions
|
||||
# and program logic
|
||||
.globl _main # Declares an instruction label as
|
||||
# global, making it accessible to
|
||||
# other files
|
||||
|
||||
_main: # MIPS programs execute instructions
|
||||
# sequentially, where the code under
|
||||
# this label will be executed firsts
|
||||
|
||||
# Let's print "hello world"
|
||||
la $a0, hello_world # Load address of string stored in
|
||||
# memory
|
||||
li $v0, 4 # Load the syscall value (indicating
|
||||
# type of functionality)
|
||||
syscall # Perform the specified syscall with
|
||||
# the given argument ($a0)
|
||||
|
||||
# Registers (used to hold data during program execution)
|
||||
# $t0 - $t9 # Temporary registers used for
|
||||
# intermediate calculations inside
|
||||
# subroutines (not saved across
|
||||
# function calls)
|
||||
|
||||
# $s0 - $s7 # Saved registers where values are
|
||||
# saved across subroutine calls.
|
||||
# Typically saved in stack
|
||||
|
||||
# $a0 - $a3 # Argument registers for passing in
|
||||
# arguments for subroutines
|
||||
# $v0 - $v1 # Return registers for returning
|
||||
# values to caller function
|
||||
|
||||
# Types of load/store instructions
|
||||
la $t0, label # Copy the address of a value in
|
||||
# memory specified by the label into
|
||||
# register $t0
|
||||
lw $t0, label # Copy a word value from memory
|
||||
lw $t1, 4($s0) # Copy a word value from an address
|
||||
# stored in a register with an offset
|
||||
# of 4 bytes (addr + 4)
|
||||
lb $t2, label # Copy a byte value to the lower order
|
||||
# portion of the register $t2
|
||||
lb $t2, 0($s0) # Copy a byte value from the source
|
||||
# address in $s0 with offset 0
|
||||
# Same idea with 'lh' for halfwords
|
||||
|
||||
sw $t0, label # Store word value into memory address
|
||||
# mapped by label
|
||||
sw $t0, 8($s0) # Store word value into address
|
||||
# specified in $s0 and offset of 8 bytes
|
||||
# Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist
|
||||
|
||||
### Math ###
|
||||
_math:
|
||||
# Remember to load your values into a register
|
||||
lw $t0, num # From the data section
|
||||
li $t0, 5 # Or from an immediate (constant)
|
||||
li $t1, 6
|
||||
add $t2, $t0, $t1 # $t2 = $t0 + $t1
|
||||
sub $t2, $t0, $t1 # $t2 = $t0 - $t1
|
||||
mul $t2, $t0, $t1 # $t2 = $t0 * $t1
|
||||
div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be
|
||||
# supported in some versons of MARS)
|
||||
div $t0, $t1 # Performs $t0 / $t1. Get the quotient
|
||||
# using 'mflo' and remainder using 'mfhi'
|
||||
|
||||
# Bitwise Shifting
|
||||
sll $t0, $t0, 2 # Bitwise shift to the left with
|
||||
# immediate (constant value) of 2
|
||||
sllv $t0, $t1, $t2 # Shift left by a variable amount in
|
||||
# register
|
||||
srl $t0, $t0, 5 # Bitwise shift to the right (does
|
||||
# not sign preserve, sign-extends with 0)
|
||||
srlv $t0, $t1, $t2 # Shift right by a variable amount in
|
||||
# a register
|
||||
sra $t0, $t0, 7 # Bitwise arithmetic shift to the right
|
||||
# (preserves sign)
|
||||
srav $t0, $t1, $t2 # Shift right by a variable amount
|
||||
# in a register
|
||||
|
||||
# Bitwise operators
|
||||
and $t0, $t1, $t2 # Bitwise AND
|
||||
andi $t0, $t1, 0xFFF # Bitwise AND with immediate
|
||||
or $t0, $t1, $t2 # Bitwise OR
|
||||
ori $t0, $t1, 0xFFF # Bitwise OR with immediate
|
||||
xor $t0, $t1, $t2 # Bitwise XOR
|
||||
xori $t0, $t1, 0xFFF # Bitwise XOR with immediate
|
||||
nor $t0, $t1, $t2 # Bitwise NOR
|
||||
|
||||
## BRANCHING ##
|
||||
_branching:
|
||||
# The basic format of these branching instructions typically follow <instr>
|
||||
# <reg1> <reg2> <label> where label is the label we want to jump to if the
|
||||
# given conditional evaluates to true
|
||||
# Sometimes it is easier to write the conditional logic backwards, as seen
|
||||
# in the simple if statement example below
|
||||
|
||||
beq $t0, $t1, reg_eq # Will branch to reg_eq if
|
||||
# $t0 == $t1, otherwise
|
||||
# execute the next line
|
||||
bne $t0, $t1, reg_neq # Branches when $t0 != $t1
|
||||
b branch_target # Unconditional branch, will always execute
|
||||
beqz $t0, req_eq_zero # Branches when $t0 == 0
|
||||
bnez $t0, req_neq_zero # Branches when $t0 != 0
|
||||
bgt $t0, $t1, t0_gt_t1 # Branches when $t0 > $t1
|
||||
bge $t0, $t1, t0_gte_t1 # Branches when $t0 >= $t1
|
||||
bgtz $t0, t0_gt0 # Branches when $t0 > 0
|
||||
blt $t0, $t1, t0_gt_t1 # Branches when $t0 < $t1
|
||||
ble $t0, $t1, t0_gte_t1 # Branches when $t0 <= $t1
|
||||
bltz $t0, t0_lt0 # Branches when $t0 < 0
|
||||
slt $s0, $t0, $t1 # Instruction that sends a signal when
|
||||
# $t0 < $t1 with reuslt in $s0 (1 for true)
|
||||
|
||||
# Simple if statement
|
||||
# if (i == j)
|
||||
# f = g + h;
|
||||
# f = f - i;
|
||||
|
||||
# Let $s0 = f, $s1 = g, $s2 = h, $s3 = i, $s4 = j
|
||||
bne $s3, $s4, L1 # if (i !=j)
|
||||
add $s0, $s1, $s2 # f = g + h
|
||||
|
||||
L1:
|
||||
sub $s0, $s0, $s3 # f = f - i
|
||||
|
||||
# Below is an example of finding the max of 3 numbers
|
||||
# A direct translation in Java from MIPS logic:
|
||||
# if (a > b)
|
||||
# if (a > c)
|
||||
# max = a;
|
||||
# else
|
||||
# max = c;
|
||||
# else
|
||||
# max = b;
|
||||
# else
|
||||
# max = c;
|
||||
|
||||
# Let $s0 = a, $s1 = b, $s2 = c, $v0 = return register
|
||||
ble $s0, $s1, a_LTE_b # if (a <= b) branch(a_LTE_b)
|
||||
ble $s0, $s2, max_C # if (a > b && a <=c) branch(max_C)
|
||||
move $v0, $s1 # else [a > b && a > c] max = a
|
||||
j done # Jump to the end of the program
|
||||
|
||||
a_LTE_b: # Label for when a <= b
|
||||
ble $s1, $s2, max_C # if (a <= b && b <= c) branch(max_C)
|
||||
move $v0, $s1 # if (a <= b && b > c) max = b
|
||||
j done # Jump to done
|
||||
|
||||
max_C:
|
||||
move $v0, $s2 # max = c
|
||||
|
||||
done: # End of program
|
||||
|
||||
## LOOPS ##
|
||||
_loops:
|
||||
# The basic structure of loops is having an exit condition and a jump
|
||||
instruction to continue its execution
|
||||
li $t0, 0
|
||||
while:
|
||||
bgt $t0, 10, end_while # While $t0 is less than 10, keep iterating
|
||||
addi $t0, $t0, 1 # Increment the value
|
||||
j while # Jump back to the beginning of the loop
|
||||
end_while:
|
||||
|
||||
# 2D Matrix Traversal
|
||||
# Assume that $a0 stores the address of an integer matrix which is 3 x 3
|
||||
li $t0, 0 # Counter for i
|
||||
li $t1, 0 # Counter for j
|
||||
matrix_row:
|
||||
bgt $t0, 3, matrix_row_end
|
||||
|
||||
matrix_col:
|
||||
bgt $t1, 3, matrix_col_end
|
||||
|
||||
# Do stuff
|
||||
|
||||
addi $t1, $t1, 1 # Increment the col counter
|
||||
matrix_col_end:
|
||||
|
||||
# Do stuff
|
||||
|
||||
addi $t0, $t0, 1
|
||||
matrix_row_end:
|
||||
|
||||
## FUNCTIONS ##
|
||||
_functions:
|
||||
# Functions are callable procedures that can accept arguments and return
|
||||
values all denoted with labels, like above
|
||||
|
||||
main: # Programs begin with main func
|
||||
jal return_1 # jal will store the current PC in $ra
|
||||
# and then jump to return_1
|
||||
|
||||
# What if we want to pass in args?
|
||||
# First we must pass in our parameters to the argument registers
|
||||
li $a0, 1
|
||||
li $a1, 2
|
||||
jal sum # Now we can call the function
|
||||
|
||||
# How about recursion?
|
||||
# This is a bit more work since we need to make sure we save and restore
|
||||
# the previous PC in $ra since jal will automatically overwrite on each call
|
||||
li $a0, 3
|
||||
jal fact
|
||||
|
||||
li $v0, 10
|
||||
syscall
|
||||
|
||||
# This function returns 1
|
||||
return_1:
|
||||
li $v0, 1 # Load val in return register $v0
|
||||
jr $ra # Jump back to old PC to continue exec
|
||||
|
||||
|
||||
# Function with 2 args
|
||||
sum:
|
||||
add $v0, $a0, $a1
|
||||
jr $ra # Return
|
||||
|
||||
# Recursive function to find factorial
|
||||
fact:
|
||||
addi $sp, $sp, -8 # Allocate space in stack
|
||||
sw $s0, ($sp) # Store reg that holds current num
|
||||
sw $ra, 4($sp) # Store previous PC
|
||||
|
||||
li $v0, 1 # Init return value
|
||||
beq $a0, 0, fact_done # Finish if param is 0
|
||||
|
||||
# Otherwise, continue recursion
|
||||
move $s0, $a0 # Copy $a0 to $s0
|
||||
sub $a0, $a0, 1
|
||||
jal fact
|
||||
|
||||
mul $v0, $s0, $v0 # Multiplication is done
|
||||
|
||||
fact_done:
|
||||
lw $s0, ($sp)
|
||||
lw $ra, ($sp) # Restore the PC
|
||||
addi $sp, $sp, 8
|
||||
|
||||
jr $ra
|
||||
|
||||
## MACROS ##
|
||||
_macros:
|
||||
# Macros are extremly useful for substituting repeated code blocks with a
|
||||
# single label for better readability
|
||||
# These are in no means substitutes for functions
|
||||
# These must be declared before it is used
|
||||
|
||||
# Macro for printing new lines (since these can be very repetitive)
|
||||
.macro println()
|
||||
la $a0, newline # New line string stored here
|
||||
li $v0, 4
|
||||
syscall
|
||||
.end_macro
|
||||
|
||||
println() # Assembler will copy that block of
|
||||
# code here before running
|
||||
|
||||
# Parameters can be passed in through macros.
|
||||
# These are denoted by a '%' sign with any name you choose
|
||||
.macro print_int(%num)
|
||||
li $v0, 1
|
||||
lw $a0, %num
|
||||
syscall
|
||||
.end_macro
|
||||
|
||||
li $t0, 1
|
||||
print_int($t0)
|
||||
|
||||
# We can also pass in immediates for macros
|
||||
.macro immediates(%a, %b)
|
||||
add $t0, %a, %b
|
||||
.end_macro
|
||||
|
||||
immediates(3, 5)
|
||||
|
||||
# Along with passing in labels
|
||||
.macro print(%string)
|
||||
la $a0, %string
|
||||
li $v0, 4
|
||||
syscall
|
||||
.end_macro
|
||||
|
||||
print(hello_world)
|
||||
|
||||
## ARRAYS ##
|
||||
.data
|
||||
list: .word 3, 0, 1, 2, 6 # This is an array of words
|
||||
char_arr: .asciiz "hello" # This is a char array
|
||||
buffer: .space 128 # Allocates a block in memory, does
|
||||
# not automatically clear
|
||||
# These blocks of memory are aligned
|
||||
# next each other
|
||||
|
||||
.text
|
||||
la $s0, list # Load address of list
|
||||
li $t0, 0 # Counter
|
||||
li $t1, 5 # Length of the list
|
||||
|
||||
loop:
|
||||
bgt $t0, $t1, end_loop
|
||||
|
||||
lw $a0, ($s0)
|
||||
li $v0, 1
|
||||
syscall # Print the number
|
||||
|
||||
addi $s0, $s0, 4 # Size of a word is 4 bytes
|
||||
addi $t0, $t0, 1 # Increment
|
||||
j loop
|
||||
end_loop:
|
||||
|
||||
## INCLUDE ##
|
||||
# You do this to import external files into your program (behind the scenes,
|
||||
# it really just takes whatever code that is in that file and places it where
|
||||
# the include statement is)
|
||||
.include "somefile.asm"
|
||||
|
||||
```
|
233
montilang.html.markdown
Normal file
233
montilang.html.markdown
Normal file
@ -0,0 +1,233 @@
|
||||
---
|
||||
language: "montilang"
|
||||
filename: montilang.ml
|
||||
contributors:
|
||||
- ["Leo Whitehead", "https://github.com/lduck11007"]
|
||||
---
|
||||
|
||||
MontiLang is a Stack-Oriented concatenative imperative programming language. Its syntax
|
||||
is roughly based off of forth with similar style for doing arithmetic in [reverse polish notation.](https://en.wikipedia.org/wiki/Reverse_Polish_notation)
|
||||
|
||||
A good way to start with MontiLang is to read the documentation and examples at [montilang.ml](http://montilang.ml),
|
||||
then download MontiLang or build from source code with the instructions provided.
|
||||
|
||||
```
|
||||
/# Monti Reference sheet #/
|
||||
/#
|
||||
Comments are multiline
|
||||
Nested comments are not supported
|
||||
#/
|
||||
/# Whitespace is all arbitrary, indentation is optional #/
|
||||
/# All programming in Monti is done by manipulating the parameter stack
|
||||
arithmetic and stack operations in MontiLang are similar to FORTH
|
||||
https://en.wikipedia.org/wiki/Forth_(programming_language)
|
||||
#/
|
||||
|
||||
/# in Monti, everything is either a string or a number. Operations treat all numbers
|
||||
similarly to floats, but anything without a remainder is treated as type int #/
|
||||
|
||||
/# numbers and strings are added to the stack from left to right #/
|
||||
|
||||
/# Arithmetic works by manipulating data on the stack #/
|
||||
|
||||
5 3 + PRINT . /# 8 #/
|
||||
|
||||
/# 5 and 3 are pushed onto the stack
|
||||
'+' replaces top 2 items on stack with sum of top 2 items
|
||||
'PRINT' prints out the top item on the stack
|
||||
'.' pops the top item from the stack.
|
||||
#/
|
||||
|
||||
6 7 * PRINT . /# 42 #/
|
||||
1360 23 - PRINT . /# 1337 #/
|
||||
12 12 / PRINT . /# 1 #/
|
||||
13 2 % PRINT . /# 1 #/
|
||||
|
||||
37 NEG PRINT . /# -37 #/
|
||||
-12 ABS PRINT . /# 12 #/
|
||||
52 23 MAX PRINT . /# 52 #/
|
||||
52 23 MIN PRINT . /# 23 #/
|
||||
|
||||
/# 'PSTACK' command prints the entire stack, 'CLEAR' clears the entire stack #/
|
||||
|
||||
3 6 8 PSTACK CLEAR /# [3, 6, 8] #/
|
||||
|
||||
/# Monti comes with some tools for stack manipulation #/
|
||||
|
||||
2 DUP PSTACK CLEAR /# [2, 2] - Duplicate the top item on the stack#/
|
||||
2 6 SWAP PSTACK CLEAR /# [6, 2] - Swap top 2 items on stack #/
|
||||
1 2 3 ROT PSTACK CLEAR /# [2, 3, 1] - Rotate top 3 items on stack #/
|
||||
2 3 NIP PSTACK CLEAR /# [3] - delete second item from the top of the stack #/
|
||||
4 5 6 TRIM PSTACK CLEAR /# [5, 6] - Deletes first item on stack #/
|
||||
/# variables are assigned with the syntax 'VAR [name]'#/
|
||||
/# When assigned, the variable will take the value of the top item of the stack #/
|
||||
|
||||
6 VAR six . /# assigns var 'six' to be equal to 6 #/
|
||||
3 6 + VAR a . /# assigns var 'a' to be equal to 9 #/
|
||||
|
||||
/# the length of the stack can be calculated with the statement 'STKLEN' #/
|
||||
1 2 3 4 STKLEN PRINT CLEAR /# 4 #/
|
||||
|
||||
/# strings are defined with | | #/
|
||||
|
||||
|Hello World!| VAR world . /# sets variable 'world' equal to string 'Hello world! #/
|
||||
|
||||
/# variables can be called by typing its name. when called, the value of the variable is pushed
|
||||
to the top of the stack #/
|
||||
world PRINT .
|
||||
|
||||
/# with the OUT statement, the top item on the stack can be printed without a newline #/
|
||||
|
||||
|world!| |Hello, | OUT SWAP PRINT CLEAR
|
||||
|
||||
/# Data types can be converted between strings and integers with the commands 'TOINT' and 'TOSTR'#/
|
||||
|5| TOINT PSTACK . /# [5] #/
|
||||
45 TOSTR PSTACK . /# ['45'] #/
|
||||
|
||||
/# User input is taken with INPUT and pushed to the stack. If the top item of the stack is a string,
|
||||
the string is used as an input prompt #/
|
||||
|
||||
|What is your name? | INPUT NIP
|
||||
|Hello, | OUT SWAP PRINT CLEAR
|
||||
|
||||
|
||||
/# FOR loops have the syntax 'FOR [condition] [commands] ENDFOR' At the moment, [condition] can
|
||||
only have the value of an integer. Either by using an integer, or a variable call to an integer.
|
||||
[commands] will be interpereted the amount of time specified in [condition] #/
|
||||
/# E.G: this prints out 1 to 10 #/
|
||||
|
||||
1 VAR a .
|
||||
FOR 10
|
||||
a PRINT 1 + VAR a
|
||||
ENDFOR
|
||||
|
||||
/# the syntax for while loops are similar. A number is evaluated as true if it is larger than
|
||||
0. a string is true if its length > 0. Infinite loops can be used by using literals.
|
||||
#/
|
||||
10 var loop .
|
||||
WHILE loop
|
||||
loop print
|
||||
1 - var loop
|
||||
ENDWHILE
|
||||
/#
|
||||
this loop would count down from 10.
|
||||
|
||||
IF statements are pretty much the same, but only are executed once.
|
||||
#/
|
||||
IF loop
|
||||
loop PRINT .
|
||||
ENDIF
|
||||
|
||||
/# This would only print 'loop' if it is larger than 0 #/
|
||||
|
||||
/# If you would want to use the top item on the stack as loop parameters, this can be done with the ':' character #/
|
||||
|
||||
/# eg, if you wanted to print 'hello' 7 times, instead of using #/
|
||||
|
||||
FOR 7
|
||||
|hello| PRINT .
|
||||
ENDFOR
|
||||
|
||||
/# this could be used #/
|
||||
7
|
||||
FOR :
|
||||
|hello| PRINT .
|
||||
ENDFOR
|
||||
|
||||
/# Equality and inequality statements use the top 2 items on the stack as parameters, and replace the top two items with the output #/
|
||||
/# If it is true, the top 2 items are replaced with '1'. If false, with '0'. #/
|
||||
|
||||
7 3 > PRINT . /# 1 #/
|
||||
2 10 > PRINT . /# 0 #/
|
||||
5 9 <= PRINT . /# 1 #/
|
||||
5 5 == PRINT . /# 1 #/
|
||||
5 7 == PRINT . /# 0 #/
|
||||
3 8 != PRINT . /# 1 #/
|
||||
|
||||
/# User defined commands have the syntax of 'DEF [name] [commands] ENDDEF'. #/
|
||||
/# eg, if you wanted to define a function with the name of 'printseven' to print '7' 10 times, this could be used #/
|
||||
|
||||
DEF printseven
|
||||
FOR 10
|
||||
7 PRINT .
|
||||
ENDFOR
|
||||
ENDDEF
|
||||
|
||||
/# to run the defined statement, simply type it and it will be run by the interpereter #/
|
||||
|
||||
printseven
|
||||
|
||||
/# Montilang supports AND, OR and NOT statements #/
|
||||
|
||||
1 0 AND PRINT . /# 0 #/
|
||||
1 1 AND PRINT . /# 1 #/
|
||||
1 0 OR PRINT . /# 1 #/
|
||||
0 0 OR PRINT . /# 0 #/
|
||||
1 NOT PRINT . /# 0 #/
|
||||
0 NOT PRINT . /# 1 #/
|
||||
|
||||
/# Preprocessor statements are made inbetween '&' characters #/
|
||||
/# currently, preprocessor statements can be used to make c++-style constants #/
|
||||
|
||||
&DEFINE LOOPSTR 20&
|
||||
/# must have & on either side with no spaces, 'DEFINE' is case sensative. #/
|
||||
/# All statements are scanned and replaced before the program is run, regardless of where the statements are placed #/
|
||||
|
||||
FOR LOOPSTR 7 PRINT . ENDFOR /# Prints '7' 20 times. At run, 'LOOPSTR' in source code is replaced with '20' #/
|
||||
|
||||
/# Multiple files can be used with the &INCLUDE <filename>& Command that operates similar to c++, where the file specified is tokenized,
|
||||
and the &INCLUDE statement is replaced with the file #/
|
||||
|
||||
/# E.G, you can have a program be run through several files. If you had the file 'name.mt' with the following data:
|
||||
|
||||
[name.mt]
|
||||
|Hello, | OUT . name PRINT .
|
||||
|
||||
a program that asks for your name and then prints it out can be defined as such: #/
|
||||
|
||||
|What is your name? | INPUT VAR name . &INCLUDE name.mt&
|
||||
|
||||
/# ARRAYS: #/
|
||||
|
||||
/# arrays are defined with the statement 'ARR'
|
||||
When called, everything currently in the stack is put into one
|
||||
array and all items on the stack are replaced with the new array. #/
|
||||
|
||||
2 3 4 ARR PSTACK . /# [[2, 3, 4]] #/
|
||||
|
||||
/# the statement 'LEN' adds the length of the last item on the stack to the stack.
|
||||
This can be used on arrays, as well as strings. #/
|
||||
|
||||
3 4 5 ARR LEN PRINT . /# 3 #/
|
||||
|
||||
/# values can be appended to an array with the statement 'APPEND' #/
|
||||
|
||||
1 2 3 ARR 5 APPEND . PRINT . /# [1, 2, 3, 5] #/
|
||||
|
||||
/# an array at the top of the stack can be wiped with the statement 'WIPE' #/
|
||||
3 4 5 ARR WIPE PRINT . /# [] #/
|
||||
|
||||
/# The last item of an array can be removed with the statement 'DROP' #/
|
||||
|
||||
3 4 5 ARR DROP PRINT . /# [3, 4]
|
||||
/# arrays, like other datatypes can be stored in variables #/
|
||||
5 6 7 ARR VAR list .
|
||||
list PRINT . /# [5, 6, 7] #/
|
||||
|
||||
/# Values at specific indexes can be changed with the statement 'INSERT <index>' #/
|
||||
4 5 6 ARR
|
||||
97 INSERT 1 . PRINT /# 4, 97, 6 #/
|
||||
|
||||
/# Values at specific indexes can be deleted with the statement 'DEL <index>' #/
|
||||
1 2 3 ARR
|
||||
DEL 1 PRINT . /# [1, 3] #/
|
||||
|
||||
/# items at certain indexes of an array can be gotten with the statement 'GET <index>' #/
|
||||
|
||||
1 2 3 ARR GET 2 PSTACK /# [[1, 2, 3], 3] #/
|
||||
```
|
||||
|
||||
## Extra information
|
||||
|
||||
- [MontiLang.ml](http://montilang.ml/)
|
||||
- [Github Page](https://github.com/lduck11007/MontiLang)
|
570
moonscript.html.markdown
Normal file
570
moonscript.html.markdown
Normal file
@ -0,0 +1,570 @@
|
||||
---
|
||||
language: moonscript
|
||||
contributors:
|
||||
- ["RyanSquared", "https://ryansquared.github.io/"]
|
||||
- ["Job van der Zwan", "https://github.com/JobLeonard"]
|
||||
filename: moonscript.moon
|
||||
---
|
||||
|
||||
MoonScript is a dynamic scripting language that compiles into Lua. It gives
|
||||
you the power of one of the fastest scripting languages combined with a
|
||||
rich set of features.
|
||||
|
||||
See [the MoonScript website](https://moonscript.org/) to see official guides on installation for all platforms.
|
||||
|
||||
```moon
|
||||
-- Two dashes start a comment. Comments can go until the end of the line.
|
||||
-- MoonScript transpiled to Lua does not keep comments.
|
||||
|
||||
-- As a note, MoonScript does not use 'do', 'then', or 'end' like Lua would and
|
||||
-- instead uses an indented syntax, much like Python.
|
||||
|
||||
--------------------------------------------------
|
||||
-- 1. Assignment
|
||||
--------------------------------------------------
|
||||
|
||||
hello = "world"
|
||||
a, b, c = 1, 2, 3
|
||||
hello = 123 -- Overwrites `hello` from above.
|
||||
|
||||
x = 0
|
||||
x += 10 -- x = x + 10
|
||||
|
||||
s = "hello "
|
||||
s ..= "world" -- s = s .. "world"
|
||||
|
||||
b = false
|
||||
b and= true or false -- b = b and (true or false)
|
||||
|
||||
--------------------------------------------------
|
||||
-- 2. Literals and Operators
|
||||
--------------------------------------------------
|
||||
|
||||
-- Literals work almost exactly as they would in Lua. Strings can be broken in
|
||||
-- the middle of a line without requiring a \.
|
||||
|
||||
some_string = "exa
|
||||
mple" -- local some_string = "exa\nmple"
|
||||
|
||||
-- Strings can also have interpolated values, or values that are evaluated and
|
||||
-- then placed inside of a string.
|
||||
|
||||
some_string = "This is an #{some_string}" -- Becomes 'This is an exa\nmple'
|
||||
|
||||
--------------------------------------------------
|
||||
-- 2.1. Function Literals
|
||||
--------------------------------------------------
|
||||
|
||||
-- Functions are written using arrows:
|
||||
|
||||
my_function = -> -- compiles to `function() end`
|
||||
my_function() -- calls an empty function
|
||||
|
||||
-- Functions can be called without using parenthesis. Parentheses may still be
|
||||
-- used to have priority over other functions.
|
||||
|
||||
func_a = -> print "Hello World!"
|
||||
func_b = ->
|
||||
value = 100
|
||||
print "The value: #{value}"
|
||||
|
||||
-- If a function needs no parameters, it can be called with either `()` or `!`.
|
||||
|
||||
func_a!
|
||||
func_b()
|
||||
|
||||
-- Functions can use arguments by preceding the arrow with a list of argument
|
||||
-- names bound by parentheses.
|
||||
|
||||
sum = (x, y)-> x + y -- The last expression is returned from the function.
|
||||
print sum(5, 10)
|
||||
|
||||
-- Lua has an idiom of sending the first argument to a function as the object,
|
||||
-- like a 'self' object. Using a fat arrow (=>) instead of a skinny arrow (->)
|
||||
-- automatically creates a `self` variable. `@x` is a shorthand for `self.x`.
|
||||
|
||||
func = (num)=> @value + num
|
||||
|
||||
-- Default arguments can also be used with function literals:
|
||||
|
||||
a_function = (name = "something", height=100)->
|
||||
print "Hello, I am #{name}.\nMy height is #{height}."
|
||||
|
||||
-- Because default arguments are calculated in the body of the function when
|
||||
-- transpiled to Lua, you can reference previous arguments.
|
||||
|
||||
some_args = (x = 100, y = x + 1000)-> print(x + y)
|
||||
|
||||
--------------------------------------------------
|
||||
-- Considerations
|
||||
--------------------------------------------------
|
||||
|
||||
-- The minus sign plays two roles, a unary negation operator and a binary
|
||||
-- subtraction operator. It is recommended to always use spaces between binary
|
||||
-- operators to avoid the possible collision.
|
||||
|
||||
a = x - 10 -- a = x - 10
|
||||
b = x-10 -- b = x - 10
|
||||
c = x -y -- c = x(-y)
|
||||
d = x- z -- d = x - z
|
||||
|
||||
-- When there is no space between a variable and string literal, the function
|
||||
-- call takes priority over following expressions:
|
||||
|
||||
x = func"hello" + 100 -- func("hello") + 100
|
||||
y = func "hello" + 100 -- func("hello" + 100)
|
||||
|
||||
-- Arguments to a function can span across multiple lines as long as the
|
||||
-- arguments are indented. The indentation can be nested as well.
|
||||
|
||||
my_func 5, -- called as my_func(5, 8, another_func(6, 7, 9, 1, 2), 5, 4)
|
||||
8, another_func 6, 7, -- called as
|
||||
9, 1, 2, -- another_func(6, 7, 9, 1, 2)
|
||||
5, 4
|
||||
|
||||
-- If a function is used at the start of a block, the indentation can be
|
||||
-- different than the level of indentation used in a block:
|
||||
|
||||
if func 1, 2, 3, -- called as func(1, 2, 3, "hello", "world")
|
||||
"hello",
|
||||
"world"
|
||||
print "hello"
|
||||
|
||||
--------------------------------------------------
|
||||
-- 3. Tables
|
||||
--------------------------------------------------
|
||||
|
||||
-- Tables are defined by curly braces, like Lua:
|
||||
|
||||
some_values = {1, 2, 3, 4}
|
||||
|
||||
-- Tables can use newlines instead of commas.
|
||||
|
||||
some_other_values = {
|
||||
5, 6
|
||||
7, 8
|
||||
}
|
||||
|
||||
-- Assignment is done with `:` instead of `=`:
|
||||
|
||||
profile = {
|
||||
name: "Bill"
|
||||
age: 200
|
||||
"favorite food": "rice"
|
||||
}
|
||||
|
||||
-- Curly braces can be left off for `key: value` tables.
|
||||
|
||||
y = type: "dog", legs: 4, tails: 1
|
||||
|
||||
profile =
|
||||
height: "4 feet",
|
||||
shoe_size: 13,
|
||||
favorite_foods: -- nested table
|
||||
foo: "ice cream",
|
||||
bar: "donuts"
|
||||
|
||||
my_function dance: "Tango", partner: "none" -- :( forever alone
|
||||
|
||||
-- Tables constructed from variables can use the same name as the variables
|
||||
-- by using `:` as a prefix operator.
|
||||
|
||||
hair = "golden"
|
||||
height = 200
|
||||
person = {:hair, :height}
|
||||
|
||||
-- Like in Lua, keys can be non-string or non-numeric values by using `[]`.
|
||||
|
||||
t =
|
||||
[1 + 2]: "hello"
|
||||
"hello world": true -- Can use string literals without `[]`.
|
||||
|
||||
--------------------------------------------------
|
||||
-- 3.1. Table Comprehensions
|
||||
--------------------------------------------------
|
||||
|
||||
-- List Comprehensions
|
||||
|
||||
-- Creates a copy of a list but with all items doubled. Using a star before a
|
||||
-- variable name or table can be used to iterate through the table's values.
|
||||
|
||||
items = {1, 2, 3, 4}
|
||||
doubled = [item * 2 for item in *items]
|
||||
-- Uses `when` to determine if a value should be included.
|
||||
|
||||
slice = [item for item in *items when i > 1 and i < 3]
|
||||
|
||||
-- `for` clauses inside of list comprehensions can be chained.
|
||||
|
||||
x_coords = {4, 5, 6, 7}
|
||||
y_coords = {9, 2, 3}
|
||||
|
||||
points = [{x,y} for x in *x_coords for y in *y_coords]
|
||||
|
||||
-- Numeric for loops can also be used in comprehensions:
|
||||
|
||||
evens = [i for i=1, 100 when i % 2 == 0]
|
||||
|
||||
-- Table Comprehensions are very similar but use `{` and `}` and take two
|
||||
-- values for each iteration.
|
||||
|
||||
thing = color: "red", name: "thing", width: 123
|
||||
thing_copy = {k, v for k, v in pairs thing}
|
||||
|
||||
-- Tables can be "flattened" from key-value pairs in an array by using `unpack`
|
||||
-- to return both values, using the first as the key and the second as the
|
||||
-- value.
|
||||
|
||||
tuples = {{"hello", "world"}, {"foo", "bar"}}
|
||||
table = {unpack tuple for tuple in *tuples}
|
||||
|
||||
-- Slicing can be done to iterate over only a certain section of an array. It
|
||||
-- uses the `*` notation for iterating but appends `[start, end, step]`.
|
||||
|
||||
-- The next example also shows that this syntax can be used in a `for` loop as
|
||||
-- well as any comprehensions.
|
||||
|
||||
for item in *points[1, 10, 2]
|
||||
print unpack item
|
||||
|
||||
-- Any undesired values can be left off. The second comma is not required if
|
||||
-- the step is not included.
|
||||
|
||||
words = {"these", "are", "some", "words"}
|
||||
for word in *words[,3]
|
||||
print word
|
||||
|
||||
--------------------------------------------------
|
||||
-- 4. Control Structures
|
||||
--------------------------------------------------
|
||||
|
||||
have_coins = false
|
||||
if have_coins
|
||||
print "Got coins"
|
||||
else
|
||||
print "No coins"
|
||||
|
||||
-- Use `then` for single-line `if`
|
||||
if have_coins then "Got coins" else "No coins"
|
||||
|
||||
-- `unless` is the opposite of `if`
|
||||
unless os.date("%A") == "Monday"
|
||||
print "It is not Monday!"
|
||||
|
||||
-- `if` and `unless` can be used as expressions
|
||||
is_tall = (name)-> if name == "Rob" then true else false
|
||||
message = "I am #{if is_tall "Rob" then "very tall" else "not so tall"}"
|
||||
print message -- "I am very tall"
|
||||
|
||||
-- `if`, `elseif`, and `unless` can evaluate assignment as well as expressions.
|
||||
if x = possibly_nil! -- sets `x` to `possibly_nil()` and evaluates `x`
|
||||
print x
|
||||
|
||||
-- Conditionals can be used after a statement as well as before. This is
|
||||
-- called a "line decorator".
|
||||
|
||||
is_monday = os.date("%A") == "Monday"
|
||||
print("It IS Monday!") if isMonday
|
||||
print("It is not Monday..") unless isMonday
|
||||
--print("It IS Monday!" if isMonday) -- Not a statement, does not work
|
||||
|
||||
--------------------------------------------------
|
||||
-- 4.1 Loops
|
||||
--------------------------------------------------
|
||||
|
||||
for i = 1, 10
|
||||
print i
|
||||
|
||||
for i = 10, 1, -1 do print i -- Use `do` for single-line loops.
|
||||
|
||||
i = 0
|
||||
while i < 10
|
||||
continue if i % 2 == 0 -- Continue statement; skip the rest of the loop.
|
||||
print i
|
||||
|
||||
-- Loops can be used as a line decorator, just like conditionals
|
||||
print "item: #{item}" for item in *items
|
||||
|
||||
-- Using loops as an expression generates an array table. The last statement
|
||||
-- in the block is coerced into an expression and added to the table.
|
||||
my_numbers = for i = 1, 6 do i -- {1, 2, 3, 4, 5, 6}
|
||||
|
||||
-- use `continue` to filter out values
|
||||
odds = for i in *my_numbers
|
||||
continue if i % 2 == 0 -- acts opposite to `when` in comprehensions!
|
||||
i -- Only added to return table if odd
|
||||
|
||||
-- A `for` loop returns `nil` when it is the last statement of a function
|
||||
-- Use an explicit `return` to generate a table.
|
||||
print_squared = (t) -> for x in *t do x*x -- returns `nil`
|
||||
squared = (t) -> return for x in *t do x*x -- returns new table of squares
|
||||
|
||||
-- The following does the same as `(t) -> [i for i in *t when i % 2 == 0]`
|
||||
-- But list comprehension generates better code and is more readable!
|
||||
|
||||
filter_odds = (t) ->
|
||||
return for x in *t
|
||||
if x % 2 == 0 then x else continue
|
||||
evens = filter_odds(my_numbers) -- {2, 4, 6}
|
||||
|
||||
--------------------------------------------------
|
||||
-- 4.2 Switch Statements
|
||||
--------------------------------------------------
|
||||
|
||||
-- Switch statements are a shorthand way of writing multiple `if` statements
|
||||
-- checking against the same value. The value is only evaluated once.
|
||||
|
||||
name = "Dan"
|
||||
|
||||
switch name
|
||||
when "Dave"
|
||||
print "You are Dave."
|
||||
when "Dan"
|
||||
print "You are not Dave, but Dan."
|
||||
else
|
||||
print "You are neither Dave nor Dan."
|
||||
|
||||
-- Switches can also be used as expressions, as well as compare multiple
|
||||
-- values. The values can be on the same line as the `when` clause if they
|
||||
-- are only one expression.
|
||||
|
||||
b = 4
|
||||
next_even = switch b
|
||||
when 1 then 2
|
||||
when 2, 3 then 4
|
||||
when 4, 5 then 6
|
||||
else error "I can't count that high! D:"
|
||||
|
||||
--------------------------------------------------
|
||||
-- 5. Object Oriented Programming
|
||||
--------------------------------------------------
|
||||
|
||||
-- Classes are created using the `class` keyword followed by an identifier,
|
||||
-- typically written using CamelCase. Values specific to a class can use @ as
|
||||
-- the identifier instead of `self.value`.
|
||||
|
||||
class Inventory
|
||||
new: => @items = {}
|
||||
add_item: (name)=> -- note the use of fat arrow for classes!
|
||||
@items[name] = 0 unless @items[name]
|
||||
@items[name] += 1
|
||||
|
||||
-- The `new` function inside of a class is special because it is called when
|
||||
-- an instance of the class is created.
|
||||
|
||||
-- Creating an instance of the class is as simple as calling the class as a
|
||||
-- function. Calling functions inside of the class uses \ to separate the
|
||||
-- instance from the function it is calling.
|
||||
|
||||
inv = Inventory!
|
||||
inv\add_item "t-shirt"
|
||||
inv\add_item "pants"
|
||||
|
||||
-- Values defined in the class - not the new() function - will be shared across
|
||||
-- all instances of the class.
|
||||
|
||||
class Person
|
||||
clothes: {}
|
||||
give_item: (name)=>
|
||||
table.insert @clothes name
|
||||
|
||||
a = Person!
|
||||
b = Person!
|
||||
|
||||
a\give_item "pants"
|
||||
b\give_item "shirt"
|
||||
|
||||
-- prints out both "pants" and "shirt"
|
||||
|
||||
print item for item in *a.clothes
|
||||
|
||||
-- Class instances have a value `.__class` that are equal to the class object
|
||||
-- that created the instance.
|
||||
|
||||
assert(b.__class == Person)
|
||||
|
||||
-- Variables declared in class body the using the `=` operator are locals,
|
||||
-- so these "private" variables are only accessible within the current scope.
|
||||
|
||||
class SomeClass
|
||||
x = 0
|
||||
reveal: ->
|
||||
x += 1
|
||||
print x
|
||||
|
||||
a = SomeClass!
|
||||
b = SomeClass!
|
||||
print a.x -- nil
|
||||
a.reveal! -- 1
|
||||
b.reveal! -- 2
|
||||
|
||||
--------------------------------------------------
|
||||
-- 5.1 Inheritance
|
||||
--------------------------------------------------
|
||||
|
||||
-- The `extends` keyword can be used to inherit properties and methods from
|
||||
-- another class.
|
||||
|
||||
class Backpack extends Inventory
|
||||
size: 10
|
||||
add_item: (name)=>
|
||||
error "backpack is full" if #@items > @size
|
||||
super name -- calls Inventory.add_item with `name`.
|
||||
|
||||
-- Because a `new` method was not added, the `new` method from `Inventory` will
|
||||
-- be used instead. If we did want to use a constructor while still using the
|
||||
-- constructor from `Inventory`, we could use the magical `super` function
|
||||
-- during `new()`.
|
||||
|
||||
-- When a class extends another, it calls the method `__inherited` on the
|
||||
-- parent class (if it exists). It is always called with the parent and the
|
||||
-- child object.
|
||||
|
||||
class ParentClass
|
||||
@__inherited: (child)=>
|
||||
print "#{@__name} was inherited by #{child.__name}"
|
||||
a_method: (a, b) => print a .. ' ' .. b
|
||||
|
||||
-- Will print 'ParentClass was inherited by MyClass'
|
||||
|
||||
class MyClass extends ParentClass
|
||||
a_method: =>
|
||||
super "hello world", "from MyClass!"
|
||||
assert super == ParentClass
|
||||
|
||||
--------------------------------------------------
|
||||
-- 6. Scope
|
||||
--------------------------------------------------
|
||||
|
||||
-- All values are local by default. The `export` keyword can be used to
|
||||
-- declare the variable as a global value.
|
||||
|
||||
export var_1, var_2
|
||||
var_1, var_3 = "hello", "world" -- var_3 is local, var_1 is not.
|
||||
|
||||
export this_is_global_assignment = "Hi!"
|
||||
|
||||
-- Classes can also be prefixed with `export` to make them global classes.
|
||||
-- Alternatively, all CamelCase variables can be exported automatically using
|
||||
-- `export ^`, and all values can be exported using `export *`.
|
||||
|
||||
-- `do` lets you manually create a scope, for when you need local variables.
|
||||
|
||||
do
|
||||
x = 5
|
||||
print x -- nil
|
||||
|
||||
-- Here we use `do` as an expression to create a closure.
|
||||
|
||||
counter = do
|
||||
i = 0
|
||||
->
|
||||
i += 1
|
||||
return i
|
||||
|
||||
print counter! -- 1
|
||||
print counter! -- 2
|
||||
|
||||
-- The `local` keyword can be used to define variables
|
||||
-- before they are assigned.
|
||||
|
||||
local var_4
|
||||
if something
|
||||
var_4 = 1
|
||||
print var_4 -- works because `var_4` was set in this scope, not the `if` scope.
|
||||
|
||||
-- The `local` keyword can also be used to shadow an existing variable.
|
||||
|
||||
x = 10
|
||||
if false
|
||||
local x
|
||||
x = 12
|
||||
print x -- 10
|
||||
|
||||
-- Use `local *` to forward-declare all variables.
|
||||
-- Alternatively, use `local ^` to forward-declare all CamelCase values.
|
||||
|
||||
local *
|
||||
|
||||
first = ->
|
||||
second!
|
||||
|
||||
second = ->
|
||||
print data
|
||||
|
||||
data = {}
|
||||
|
||||
--------------------------------------------------
|
||||
-- 6.1 Import
|
||||
--------------------------------------------------
|
||||
|
||||
-- Values from a table can be brought to the current scope using the `import`
|
||||
-- and `from` keyword. Names in the `import` list can be preceded by `\` if
|
||||
-- they are a module function.
|
||||
|
||||
import insert from table -- local insert = table.insert
|
||||
import \add from state: 100, add: (value)=> @state + value
|
||||
print add 22
|
||||
|
||||
-- Like tables, commas can be excluded from `import` lists to allow for longer
|
||||
-- lists of imported items.
|
||||
|
||||
import
|
||||
asdf, gh, jkl
|
||||
antidisestablishmentarianism
|
||||
from {}
|
||||
|
||||
--------------------------------------------------
|
||||
-- 6.2 With
|
||||
--------------------------------------------------
|
||||
|
||||
-- The `with` statement can be used to quickly call and assign values in an
|
||||
-- instance of a class or object.
|
||||
|
||||
file = with File "lmsi15m.moon" -- `file` is the value of `set_encoding()`.
|
||||
\set_encoding "utf8"
|
||||
|
||||
create_person = (name, relatives)->
|
||||
with Person!
|
||||
.name = name
|
||||
\add_relative relative for relative in *relatives
|
||||
me = create_person "Ryan", {"sister", "sister", "brother", "dad", "mother"}
|
||||
|
||||
with str = "Hello" -- assignment as expression! :D
|
||||
print "original: #{str}"
|
||||
print "upper: #{\upper!}"
|
||||
|
||||
--------------------------------------------------
|
||||
-- 6.3 Destructuring
|
||||
--------------------------------------------------
|
||||
|
||||
-- Destructuring can take arrays, tables, and nested tables and convert them
|
||||
-- into local variables.
|
||||
|
||||
obj2 =
|
||||
numbers: {1, 2, 3, 4}
|
||||
properties:
|
||||
color: "green"
|
||||
height: 13.5
|
||||
|
||||
{numbers: {first, second}, properties: {:color}} = obj2
|
||||
|
||||
print first, second, color -- 1 2 green
|
||||
|
||||
-- `first` and `second` return [1] and [2] because they are as an array, but
|
||||
-- `:color` is like `color: color` so it sets itself to the `color` value.
|
||||
|
||||
-- Destructuring can be used in place of `import`.
|
||||
|
||||
{:max, :min, random: rand} = math -- rename math.random to rand
|
||||
|
||||
-- Destructuring can be done anywhere assignment can be done.
|
||||
|
||||
for {left, right} in *{{"hello", "world"}, {"egg", "head"}}
|
||||
print left, right
|
||||
```
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Language Guide](https://moonscript.org/reference/)
|
||||
- [Online Compiler](https://moonscript.org/compiler/)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user