diff options
-rw-r--r-- | awk.html.markdown | 2 | ||||
-rw-r--r-- | dart.html.markdown | 2 | ||||
-rw-r--r-- | elisp.html.markdown | 17 | ||||
-rw-r--r-- | es-es/awk-es.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/awk-fr.html.markdown | 2 | ||||
-rw-r--r-- | go.html.markdown | 2 | ||||
-rw-r--r-- | haskell.html.markdown | 3 | ||||
-rw-r--r-- | java.html.markdown | 11 | ||||
-rw-r--r-- | javascript.html.markdown | 8 | ||||
-rw-r--r-- | jquery.html.markdown | 2 | ||||
-rw-r--r-- | kotlin.html.markdown | 2 | ||||
-rw-r--r-- | pt-br/awk-pt.html.markdown | 2 | ||||
-rw-r--r-- | python.html.markdown | 84 | ||||
-rw-r--r-- | rst.html.markdown | 2 | ||||
-rw-r--r-- | rust.html.markdown | 3 | ||||
-rw-r--r-- | tact.html.markdown | 603 | ||||
-rw-r--r-- | xml.html.markdown | 2 | ||||
-rw-r--r-- | yaml.html.markdown | 4 | ||||
-rw-r--r-- | zh-cn/awk-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/c-cn.html.markdown | 2 |
20 files changed, 706 insertions, 51 deletions
diff --git a/awk.html.markdown b/awk.html.markdown index dc22a2bd..e1d4a0a3 100644 --- a/awk.html.markdown +++ b/awk.html.markdown @@ -209,7 +209,7 @@ function string_functions( localvar, arr) { # 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" + 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 diff --git a/dart.html.markdown b/dart.html.markdown index 69e1623d..282f183b 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -45,7 +45,7 @@ const CONSTANT_VALUE = "I CANNOT CHANGE"; CONSTANT_VALUE = "DID I?"; //Error /// Final is another variable declaration that cannot be change once it has been instantiated. Commonly used in classes and functions /// `final` can be declared in pascalCase. -final finalValue = "value cannot be change once instantiated"; +final finalValue = "value cannot be changed once instantiated"; finalValue = "Seems not"; //Error /// `var` is another variable declaration that is mutable and can change its value. Dart will infer types and will not change its data type diff --git a/elisp.html.markdown b/elisp.html.markdown index f839dac0..5d98ceff 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -3,6 +3,7 @@ language: elisp contributors: - ["Bastien Guerry", "https://bzg.fr"] - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] + - ["rilysh", "https://github.com/rilysh"] filename: learn-emacs-lisp.el --- @@ -12,11 +13,11 @@ filename: learn-emacs-lisp.el ;; First make sure you read this text by Peter Norvig: ;; http://norvig.com/21-days.html ;; -;; Then install GNU Emacs 24.3: +;; Then install latest version of GNU Emacs: ;; ;; Debian: apt-get install emacs (or see your distro instructions) -;; OSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg -;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip +;; OSX: https://emacsformacosx.com/ +;; Windows: https://ftp.gnu.org/gnu/emacs/windows/ ;; ;; More general information can be found at: ;; http://www.gnu.org/software/emacs/#Obtaining @@ -76,12 +77,12 @@ filename: learn-emacs-lisp.el ;; `C-j' inserts the result of the evaluation in the buffer. ;; `C-xC-e' displays the same result in Emacs bottom line, -;; called the "minibuffer". We will generally use `C-xC-e', +;; called the "echo area". We will generally use `C-xC-e', ;; as we don't want to clutter the buffer with useless text. ;; `setq' stores a value into a variable: (setq my-name "Bastien") -;; `C-xC-e' => "Bastien" (displayed in the mini-buffer) +;; `C-xC-e' => "Bastien" (displayed in the echo area) ;; `insert' will insert "Hello!" where the cursor is: (insert "Hello!") @@ -343,3 +344,9 @@ filename: learn-emacs-lisp.el ;; To read an online introduction to Emacs Lisp: ;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html ``` + +### Further Reading +- [GNU Elisp Manual](https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html) +- [Emacs Wiki](https://www.emacswiki.org/emacs/LearningEmacs) +- [Emacs Docs](https://emacsdocs.org/docs/elisp/Emacs-Lisp) +- [Mpre Elisp Docs](https://www.math.utah.edu/docs/info/elisp_22.html) diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 725dae1d..1ee12956 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -196,7 +196,7 @@ function string_functions( localvar, arr) { # Ambas regresan el número de matches remplazados. 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" + gsub("e", ".", localvar) # localvar => "M..t m. at th. bar" # Buscar una cadena que haga match con una expresión regular # index() hace lo mismo, pero no permite expresiones regulares diff --git a/fr-fr/awk-fr.html.markdown b/fr-fr/awk-fr.html.markdown index a5db24b2..bd4e1312 100644 --- a/fr-fr/awk-fr.html.markdown +++ b/fr-fr/awk-fr.html.markdown @@ -217,7 +217,7 @@ function string_functions( localvar, arr) { # Les deux renvoient le nombre de correspondances remplacées 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" + gsub("e", ".", localvar); # localvar => "M..t m. at th. bar" # Rechercher une chaîne de caractères qui correspond à une expression # régulière index() fait la même chose, mais n'autorise pas les expressions diff --git a/go.html.markdown b/go.html.markdown index fe69ed43..9dbfefaa 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -46,7 +46,7 @@ package main import ( "fmt" // A package in the Go standard library. "io/ioutil" // Implements some I/O utility functions. - "math" // Math library with local alias m. + m "math" // Math library with local alias m. "net/http" // Yes, a web server! "os" // OS functions like working with the file system "strconv" // String conversions. diff --git a/haskell.html.markdown b/haskell.html.markdown index 29712570..edb4121d 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -3,6 +3,7 @@ language: Haskell filename: learnhaskell.hs contributors: - ["Adit Bhargava", "http://adit.io"] + - ["Stanislav Modrak", "https://stanislav.gq"] --- Haskell was designed as a practical, purely functional programming @@ -602,6 +603,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater There are two popular ways to install Haskell: The traditional [Cabal-based installation](http://www.haskell.org/platform/), and the newer [Stack-based process](https://www.stackage.org/install). You can find a much gentler introduction from the excellent -[Learn you a Haskell](http://learnyouahaskell.com/), +[Learn you a Haskell](http://learnyouahaskell.com/) (or [up-to-date community version](https://learnyouahaskell.github.io/)), [Happy Learn Haskell Tutorial](http://www.happylearnhaskelltutorial.com/) or [Real World Haskell](http://book.realworldhaskell.org/). diff --git a/java.html.markdown b/java.html.markdown index 4be940be..6003f8ef 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -91,6 +91,9 @@ public class LearnJava { int numInt = scanner.nextInt(); // read long input + long numLong = scanner.nextLong(); + + // read float input float numFloat = scanner.nextFloat(); // read double input @@ -182,7 +185,7 @@ public class LearnJava { // // BigInteger is a data type that allows programmers to manipulate // integers longer than 64-bits. Integers are stored as an array of - // of bytes and are manipulated using functions built into BigInteger + // bytes and are manipulated using functions built into BigInteger // // BigInteger can be initialized using an array of bytes or a string. BigInteger fooBigInteger = new BigInteger(fooByteArray); @@ -314,7 +317,7 @@ public class LearnJava { System.out.println("1/2.0 = " + (i1 / (double)i2)); // => 0.5 // Modulo - System.out.println("11%3 = "+(11 % 3)); // => 2 + System.out.println("11%3 = " + (11 % 3)); // => 2 // Comparison operators System.out.println("3 == 2? " + (3 == 2)); // => false @@ -368,7 +371,7 @@ public class LearnJava { // While loop int fooWhile = 0; - while(fooWhile < 100) { + while (fooWhile < 100) { System.out.println(fooWhile); // Increment the counter // Iterated 100 times, fooWhile 0,1,2...99 @@ -383,7 +386,7 @@ public class LearnJava { // Increment the counter // Iterated 100 times, fooDoWhile 0->99 fooDoWhile++; - } while(fooDoWhile < 100); + } while (fooDoWhile < 100); System.out.println("fooDoWhile Value: " + fooDoWhile); // For Loop diff --git a/javascript.html.markdown b/javascript.html.markdown index 41ed7dea..cb530bbb 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -105,6 +105,10 @@ false; "1, 2, " + 3; // = "1, 2, 3" "Hello " + ["world", "!"]; // = "Hello world,!" +// ...which can result in some weird behaviour... +13 + !0; // 14 +"13" + !0; // '13true' + // and are compared with < and > "a" < "b"; // = true @@ -116,10 +120,6 @@ null == undefined; // = true "5" === 5; // = false null === undefined; // = false -// ...which can result in some weird behaviour... -13 + !0; // 14 -"13" + !0; // '13true' - // You can access characters in a string with `charAt` "This is a string".charAt(0); // = 'T' diff --git a/jquery.html.markdown b/jquery.html.markdown index 18077dca..cdcb89d9 100644 --- a/jquery.html.markdown +++ b/jquery.html.markdown @@ -12,8 +12,8 @@ jQuery is a JavaScript library that helps you "do more, write less". It makes ma Because jQuery is a JavaScript library you should [learn JavaScript first](https://learnxinyminutes.com/docs/javascript/) **NOTE**: jQuery has fallen out of the limelight in recent years, since you can achieve the same thing with the vanilla DOM (Document Object Model) API. So the only thing it is used for is a couple of handy features, such as the [jQuery date picker](https://api.jqueryui.com/datepicker) (which actually has a standard, unlike the `<input type="date">` HTML element), and the obvious decrease in the code length. -```js +```js /////////////////////////////////// // 1. Selectors diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 12008074..6ca2dcf2 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -297,7 +297,7 @@ fun helloWorld(val name : String) { else -> println("none of the above") } - // "when" can be used as a function that returns a value. + // "when" can be used as an expression that returns a value. var result = when (i) { 0, 21 -> "0 or 21" in 1..20 -> "in the range 1 to 20" diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown index 597b0e7a..02bffc41 100644 --- a/pt-br/awk-pt.html.markdown +++ b/pt-br/awk-pt.html.markdown @@ -202,7 +202,7 @@ function string_functions( localvar, arr) { # Ambas retornam o número de instâncias substituídas 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" + gsub("e", ".", localvar) # localvar => "M..t m. at th. bar" # Localiza um texto que casa com uma expressão regular # index() faz a mesma coisa, mas não permite uma expressão regular diff --git a/python.html.markdown b/python.html.markdown index d9eda60c..326ddb95 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -685,8 +685,8 @@ print(math.sqrt(16)) # => 4.0 # You can get specific functions from a module from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 +print(ceil(3.7)) # => 4 +print(floor(3.7)) # => 3 # You can import all functions from a module. # Warning: this is not recommended @@ -733,7 +733,9 @@ class Human: self.name = name # Initialize property - self._age = 0 + self._age = 0 # the leading underscore indicates the "age" property is + # intended to be used internally + # do not rely on this to be enforced: it's a hint to other devs # An instance method. All methods take "self" as the first argument def say(self, msg): @@ -876,7 +878,8 @@ if __name__ == '__main__': if type(sup) is Superhero: print('I am a superhero') - # Get the Method Resolution search Order used by both getattr() and super() + # Get the "Method Resolution Order" used by both getattr() and super() + # (the order in which classes are searched for an attribute or method) # This attribute is dynamic and can be updated print(Superhero.__mro__) # => (<class '__main__.Superhero'>, # => <class 'human.Human'>, <class 'object'>) @@ -958,8 +961,7 @@ class Batman(Superhero, Bat): if __name__ == '__main__': sup = Batman() - # Get the Method Resolution search Order used by both getattr() and super(). - # This attribute is dynamic and can be updated + # The Method Resolution Order print(Batman.__mro__) # => (<class '__main__.Batman'>, # => <class 'superhero.Superhero'>, # => <class 'human.Human'>, @@ -1016,31 +1018,67 @@ gen_to_list = list(values) print(gen_to_list) # => [-1, -2, -3, -4, -5] -# Decorators -# In this example `beg` wraps `say`. If say_please is True then it -# will change the returned message. -from functools import wraps +# Decorators are a form of syntactic sugar. +# They make code easier to read while accomplishing clunky syntax. +# Wrappers are one type of decorator. +# They're really useful for adding logging to existing functions without needing to modify them. -def beg(target_function): - @wraps(target_function) +def log_function(func): def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - + print("Entering function", func.__name__) + result = func(*args, **kwargs) + print("Exiting function", func.__name__) + return result return wrapper +@log_function # equivalent: +def my_function(x,y): # def my_function(x,y): + return x+y # return x+y + # my_function = log_function(my_function) +# The decorator @log_function tells us as we begin reading the function definition +# for my_function that this function will be wrapped with log_function. +# When function definitions are long, it can be hard to parse the non-decorated +# assignment at the end of the definition. + +my_function(1,2) # => "Entering function my_function" + # => "3" + # => "Exiting function my_function" + +# But there's a problem. +# What happens if we try to get some information about my_function? + +print(my_function.__name__) # => 'wrapper' +print(my_function.__code__.co_argcount) # => 0. The argcount is 0 because both arguments in wrapper()'s signature are optional. + +# Because our decorator is equivalent to my_function = log_function(my_function) +# we've replaced information about my_function with information from wrapper + +# Fix this using functools + +from functools import wraps + +def log_function(func): + @wraps(func) # this ensures docstring, function name, arguments list, etc. are all copied + # to the wrapped function - instead of being replaced with wrapper's info + def wrapper(*args, **kwargs): + print("Entering function", func.__name__) + result = func(*args, **kwargs) + print("Exiting function", func.__name__) + return result + return wrapper -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please +@log_function +def my_function(x,y): + return x+y + +my_function(1,2) # => "Entering function my_function" + # => "3" + # => "Exiting function my_function" +print(my_function.__name__) # => 'my_function' +print(my_function.__code__.co_argcount) # => 2 -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` ### Free Online diff --git a/rst.html.markdown b/rst.html.markdown index c177fdb4..8a730c7a 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -8,7 +8,7 @@ filename: restructuredtext.rst RST, Restructured Text, is a file format created by the Python community to write documentation. It is part of [Docutils](https://docutils.sourceforge.io/rst.html). -RST is a markdown language like HTML but is much more lightweight and easier to read. +RST is a markup language like HTML but is much more lightweight and easier to read. ## Installation diff --git a/rust.html.markdown b/rust.html.markdown index c677ed96..526d20d5 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -30,6 +30,9 @@ Rust not only fast, but also easy and efficient to code in. // This is a comment. Line comments look like this... // and extend multiple lines like this. +/* Block comments + /* can be nested. */ */ + /// Documentation comments look like this and support markdown notation. /// # Examples /// diff --git a/tact.html.markdown b/tact.html.markdown new file mode 100644 index 00000000..2cb650ee --- /dev/null +++ b/tact.html.markdown @@ -0,0 +1,603 @@ +--- +language: Tact +filename: tact.tc +contributors: + - ["Tal Kol", "https://www.orbs.com/"] + - ["Kirill Malev", "https://fslabs.io"] + - ["Yash Garg", "https://github.com/yash0501"] +--- + +Tact language is used to program smart contracts on the +[The Open Network](https://ton.org) blockchain. Contract logic is executed in +TVM, the stack-based TON Virtual Machine. + +Tact is a statically typed, but language was designed to be friendly for +developers with JS and Python background. + +This page is based on [Tact-by-Example](https://tact-by-example.org/). +You can use this resource to play around with contracts and check out +the interactive features. + +# Basic syntax, function definition + +```c +// Single line comment + + // This is a multi-line comment + // this is a comment in the comment + + get fun greeting(): String { + // This is a function that returns "hello world" message + // Return type is specified after a colon : + return "hello world"; + } +``` + +# A Simple Counter contract + +This is a simple counter contract that allows users to increment its value. + +This contract has a state variable `val` that persists between contract calls + +- the counter value. When persisted, this variable is encoded as `uint32` - + a 32-bit unsigned integer. Contracts pay rent in proportion to the amount + of persistent space they consume, so compact representations are encouraged. + +State variables should be initialized in `init()` that runs on deployment of +the contract. + +## Messages + +The actor model is a model of concurrent computation and is at the heart of TON +smart contracts. Each smart contract can process one message at a time, change +its own state, or send one or several messages. Processing of the message +occurs in one transaction, that is, it cannot be interrupted. Messages to one +contract are processed consequently one by one. As a result, the execution of +each transaction is local and can be parallelized at the blockchain level, +which allows for on-demand throughput horizontal scaling and hosting an +unlimited number of users and transactions. + +## Receiving messages + +This contract can receive messages from users. Unlike getters that are just +read-only, messages can do write operations and change the contract's +persistent state. Incoming messages are processed in receive() methods as +transactions and cost gas for the sender. + +After deploying the contract, send the increment message by pressing the Send +increment button in order to increase the counter value by one. Afterwards, +call the getter value() to see that the value indeed changed. + +```c +contract Counter { +// Tact allows to create a contract + // persistent state variable of type Int to hold the counter value + val: Int as uint32; + + // initialize the state variable when contract is deployed + init() { + self.val = 0; + } + + // handler for incoming increment messages that change the state + receive("increment") { + self.val = self.val + 1; + } + + // read-only getter for querying the counter value + get fun value(): Int { + return self.val; + } +} +``` + +# The Deployable Trait + +Tact doesn't support classical class inheritance, but contracts can implement +traits. One of the commonly used traits is `Deployable`. It implements a simple +receiver for the Deploy message which helps deploy contracts in a standard way. + +All contracts are deployed by sending them a message. This can be any message, +but best practice is to designate the special `Deploy` +message for this purpose. + +This message has a single field, `queryId`, which is provided by the deployer +(normally zero). If the deploy succeeds, the contract will reply with the +message `DeployOk` and echo the same `queryId` in the response. + +If you're using Tact's [auto-generated](https://docs.tact-lang.org/tools/typescript#tact-contract-in-typescript) TypeScript +classes to deploy, sending the deploy message should look like: + +```c +const msg = { $$type: "Deploy", queryId: 0n }; + await contract.send(sender, { value: toNano(1) }, msg); +``` + +You can see the implementation of the trait [here](https://github.com/tact-lang/tact/blob/main/stdlib/libs/deploy.tact). +Notice that the file deploy.tact needs to be imported from the standard +library using the import keyword. + +```c +// this trait has to be imported +import "@stdlib/deploy"; + +// the Deployable trait adds a default receiver for the "Deploy" message +contract Counter with Deployable { + + val: Int as uint32; + + init() { + self.val = 0; + } + + receive("increment") { + self.val = self.val + 1; + } + + get fun value(): Int { + return self.val; + } +} +``` + +# Integers + +Tact supports a number of primitive data types that are tailored for +smart contract use. + +`Int` is the primary number type. Math in smart contracts is always done +with integers and never with floating points since floats are [unpredictable](https://learn.microsoft.com/en-us/cpp/build/why-floating-point-numbers-may-lose-precision). + +The runtime type `Int` is always 257-bit signed, so all runtime calculations +are done at 257-bit. This should be large enough for pretty much anything you +need as it's large enough to hold the number of atoms in the universe. + +Persistent state variables can be initialized inline or inside `init()`. +If you forget to initialize a state variable, the code will not compile. + +## State costs + +When encoding `Int` to persistent state, we will usually use smaller +representations than 257-bit to reduce storage cost. +The persistent state size is specified in every declaration of +a state variable after the `as` keyword. + +Storing 1000 257-bit integers in state [costs](https://ton.org/docs/develop/smart-contracts/fees#how-to-calculate-fees) about +0.184 TON per year. Storing 1000 32-bit integers only costs +0.023 TON per year by comparison. + +```c +import "@stdlib/deploy"; + +contract Integers with Deployable { + + // contract persistent state variables + // integers can be persisted in state in various sizes + // range -2^256 to 2^256 - 1 (takes 257 bit = 32 bytes + 1 bit) + i1: Int as int257 = 3001; + i2: Int as uint256; // range 0 to 2^256 - 1 (takes 256 bit = 32 bytes) + // range -2^255 to 2^255 - 1 (takes 256 bit = 32 bytes) + i3: Int as int256 = 17; + i4: Int as uint128; // range 0 to 2^128 - 1 (takes 128 bit = 16 bytes) + // range -2^127 to 2^127 - 1 (takes 128 bit = 16 bytes) + i5: Int as int128; + i6: Int as coins; // range 0 to 2^120 - 1 (takes 120 bit = 15 bytes) + // range 0 to 18,446,744,073,709,551,615 (takes 64 bit = 8 bytes) + i7: Int as uint64 = 0x1c4a; + // range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 + // (takes 64 bit = 8 bytes) + i8: Int as int64 = -203; + i9: Int as uint32 = 0; // range 0 to 4,294,967,295 (takes 32 bit = 4 bytes) + // range -2,147,483,648 to 2,147,483,647 (takes 32 bit = 4 bytes) + i10: Int as int32 = 0; + i11: Int as uint16 = 0; // range 0 to 65,535 (takes 16 bit = 2 bytes) + i12: Int as int16 = 0; // range -32,768 to 32,767 (takes 16 bit = 2 bytes) + i13: Int as uint8 = 0; // range 0 to 255 (takes 8 bit = 1 byte) + i14: Int as int8 = 0; // range -128 to 127 (takes 8 bit = 1 byte) + + init() { + // we can define numbers in hex (base 16) + self.i2 = 0x83dfd552e6372; + self.i4 = 1507998500293440234999; // we can define numbers in decimal + self.i5 = pow(10, 9); // this is 10^9 = 1,000,000,000 + self.i6 = ton("1.23"); // easy to read coin balances + // (coins type is nano-tons, like cents, just with 9 decimals) + } + + receive("show all") { + dump(self.i1); + dump(self.i2); + dump(self.i3); + dump(self.i4); + dump(self.i5); + dump(self.i6); + dump(self.i7); + dump(self.i8); + } + + get fun result(): Int { + return self.i1; + } +} +``` + +## Bools, Addresses, Strings, Operators and Constants + +### Bool + +Bool can be used for boolean variables + +```js +b1: Bool = true; +b2: Bool = false; +``` + +### Address + +Address is another primitive data type. It represents standard addresses on +the TON blockchain. +TON is divided into multiple chains called workchains. One of the internal +fields of the address is the workchain id: +0 - The standard workchain, for regular users. Your contracts will be here. +-1 - The masterchain, usually for validators. + +```js +// bouncable (same foundation wallet) +a1: Address = address("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N"); +// non-bounceable (same foundation wallet) +a2: Address = address("UQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqEBI"); +``` + +### String + +Tact has basic support for strings. Strings support unicode and don't +have any special escape characters like \n. +Strings are immutable. Once a sequence of characters is created, this +sequence cannot be modified. +If you need to concatenate strings in run-time, you can use a StringBuilder. +This object handles gas efficiently and supports append() of various types to +the string. + +```js +s1: String = "hello world"; +sb: StringBuilder = beginString(); +sb.append(self.s1); +``` + +### Integer Operations + +Addition, subtraction, multiplication, division, modulo, +shift left and right, minimum and maximum numbers, absolute value + +```js +i: Int = -12; // temporary variable, runtime Int type is always int257 +i = i1 * 3 + (i2 - i); // basic math expressions +i = i1 % 10; // modulo (remainder after division), 3001 % 10 = 1 +i = i1 / 1000; // integer division (truncation toward zero), 3001 / 1000 = 3 +i = i1 >> 3; // shift right (multiply by 2^n) +i = i1 << 2; // shift left (divide by 2^n) +i = min(i2, 11); // minimum between two numbers +i = max(i2, 66); // maximum between two numbers +i = abs(-1 * i2); // absolute value +``` + +### Constants + +Unlike variables, constants cannot change. Their values are +calculated in compile-time and cannot change during execution. + +```js +const StateUnpaid: Int = 0; +``` + +## Getters, Receivers and Messages + +### Getters + +Getters are special contract functions that allow users to query +information from the contract. +Contract methods starting with the prefix get fun are all getters. +Calling getters is free and does not cost gas. +Getters are read-only, they cannot change the contract persistent state. +A contract cannot execute a getter of another contract. Getters are only +executable by end-users off-chain. + +```js +count: Int as uint32 = 17; + +get fun counter(): Int { + return self.count; +} +``` + +### Receivers + +Contract methods named receive() are the handlers that process +each incoming message type. +Tact will automatically route every incoming message to the correct receiver +listening for it according to its type. A message is only handled by one receiver. + +Handler for "increment" textual message - this is a textual string message, +these cannot carry input arguments + +```js +receive("increment") { + self.val = self.val + 1; +} +``` + +### Messages + +Messages are defined using the message keyword. They can carry input +arguments. For integers, you must define the encoding size, just like in +state variables. + +Handler for the "Add" message - this is a binary message that has an input +argument (amount) + +```js +receive(msg: Add) { + self.val = self.val + msg.amount; +} +``` + +## Structs + +Structs allow you to combine multiple primitives together in a more semantic way. +Structs can define complex data types that contain multiple fields of +different types. They can also be nested. + +```js +// Normal struct +struct Point { + x: Int as int64; + y: Int as int64; +} + +// Nested struct +struct Params { + name: String = "Satoshi"; // default value + age: Int? = null; // optional field + point: Point; // nested structs +} +``` + +## Message Sender and Throwing Errors + +### Message Sender + +Every incoming message is sent from some contract that has +an address. You can query the address of the message sender by calling sender() + +```js +deployer: Address = sender(); +``` + +### Errors + +When an error is thrown, the transaction reverts. By writing a +require() on a condition that isn't met + +```js +require(self.val < 5, "Counter is too high"); +``` + +## Messages Between Contracts, Sending and Receiving TON Coins + +### Messages Between Contracts + +Different contracts can only communicate with +each other by sending each other messages. + +This example sends a message to the to address with value of 1 TON and body +of a comment with a string "Hello, World!". +SendIgnoreErrors means that even when error occurs during message sending +next messages would be sent anyway. + +```js +let to: Address = ...; +let value: Int = ton("1"); +send(SendParameters{ + to: to, // address of receiver + value: value, // amount of TON you want to send + mode: SendIgnoreErrors, // 8-bit flag configuring how to send message + bounce: true, // if set to true (default) then message + // will be bounced back to sender + body: "Hello, World!".asComment() // message body as Cell +}); +``` + +### Receiving TONs + +You can query the contract balance with myBalance() - note +that the value is in nano-tons (like cents, just with 9 decimals). The balance +already contains the incoming message value. +You can also get the incoming TON balance with context().value + +```js +val: Int as int64 = myBalance() +// or +// print how much TON coin were sent with this message +dump(context().value); +``` + +### Sending TONs + +We can send any amount of TON to any address just like we created +a send call between different contracts + +Send mode SendRemainingValue will add to the outgoing value any excess left +from the incoming message after all gas costs are deducted from it. + +```js +amount: Int as coins = ton("1"); +send(SendParameters{ + to: sender(), + bounce: true, + value: amount, + mode: SendRemainingValue + SendIgnoreErrors +}); +``` + +## If/Else statements and Loops + +### If + +Tact supports if statements in a similar syntax to most programming +languages. Curly braces are required. +We can have the else and else if similar to other programming languages. + +```js +if (val > 1000) { + dump("larger than 1000"); +} else if (val > 500) { + dump("between 500 and 1000"); +} else { + dump("smaller than 500"); +} +``` + +### Loops + +Tact does not support traditional 'for' loops, 'break' and 'continue' +statements in loops. +The repeat loop statement input number must fit within an int32. + +```js +// repeat exactly 10 times + +repeat (10) { + i = i + 1; + sum = sum + i; +} + +// While loop + +let x: Int = 10; +while(x > 0) { + x = x - 1; +} + +// do-until loop + +let x: Int = 10; +do { + x = x - 1; +} until (x <= 0); +``` + +## Functions + +Functions in Tact start with the fun keyword. Functions can receive multiple +input arguments and can optionally return a single output value. You can +return a struct if you want to return multiple values. + +```js +fun average(a: Int, b: Int): Int { + return (a + b) / 2; +} +``` + +## Maps and Arrays + +### Maps + +Maps are a dictionary type that can hold an arbitrary number of items, +each under a different key. +The keys in maps can either be an Int type or an Address type. +You can check if a key is found in the map by calling the get() method. +Replace the value under a key by calling the set() method. + +```js +mi1: map<Int, TokenInfo>; // maps with Int as key +ma1: map<Address, TokenInfo>; // maps with Address as key +``` + +### Arrays + +To create an array, define a map with 'Int' type as key as well as value. + +```js +arr: map<Int, Int>; // this is our array implemented with a map +``` + +## Ownable Standard Library + +The Ownable trait allows the contract to set an owner role, which can have +higher priviliges from everybody else. +For this you would need to import the "@stdlib/ownable" library and inherit +it in your contract + +- Use the self.requireOwner() call to verify that the person making that + function call is the owner of contract +- 'ChangeOwner{newOwner: Address}' message which allows the owner to + transfer ownership. +- Define state variables named 'owner: Address' and 'stopped: Bool' and + call 'self.requireNotStopped()' on actions that should be stopped. +- Define state variables named 'owner: Address' and "stopped: Bool' and + call 'self.requireNotStopped()' on actions that should be stopped. + +```js +import "@stdlib/ownable"; +import "@stdlib/deploy"; + +contract Counter with Deployable, Ownable { + owner: Address; + + init() { // initialize a contract with default values like 'constructor' + self.owner = sender(); // we can initialize owner to any value we want, the deployer in this case + self.val = 0; + } + + // this message in only available to the owner + receive("double") { + self.requireOwner(); + self.val = self.val * 2; + } + + // this message will only work until the contract was stopped + receive("increment") { + self.requireNotStopped(); + self.val = self.val + 1; + } + + // this message will only work as long as the contract is not stopped + receive("increment2") { + self.requireNotStopped(); + self.val = self.val + 1; + } +} + +``` + +## Additional resources + +- [TON Documentation](https://ton.org/docs/#/) +- [Tact Docs](https://docs.tact-lang.org/) +- [Tact by Example](https://tact-by-example.org/) +- [Community portal](https://society.ton.org) +- [Blockchain portal](https://ton.org) +- [Stackoverflow](https://stackoverflow.com/questions/tagged/ton) + +## Social + +- [Tact community](https://t.me/tactlang) +- [Developer community](https://t.me/tondev_eng) +- [TON Learn](https://t.me/ton_learn) +- [Tondev News](https://t.me/tondevnews) +- [TON Technical Updates](https://t.me/thetontech) + +## Useful blogposts + +- [Setting up a TON Development Environment](https://society.ton.org/setting-up-a-ton-development-environment) +- [Hello World on TON](https://society.ton.org/ton-hello-world-step-by-step-guide-for-writing-your-first-smart-contract-in-func) + +## Future To Dos + +- Add smart contracts examples +- Add more links to documentations + +This file is based on [Tact By Example](https://tact-by-example.org). + +P.S. If by any chance you're familiar with [Forth](https://learnxinyminutes.com/docs/forth/), +you can also take a look at [Fift](https://ton-blockchain.github.io/docs/fiftbase.pdf). diff --git a/xml.html.markdown b/xml.html.markdown index 2a258d94..630e4c90 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -165,7 +165,7 @@ Support for DTDs is ubiquitous because they are so old. Unfortunately, modern XM ## Further Reading -* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/) +* [XML Schema Definitions Tutorial](https://www.w3schools.com/xml/schema_intro.asp) * [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp) * [XML Tutorial](http://www.w3schools.com/xml/default.asp) * [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp) diff --git a/yaml.html.markdown b/yaml.html.markdown index 135213d2..2bb35d42 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -44,8 +44,8 @@ key with spaces: value # Yes and No (doesn't matter the case) will be evaluated to boolean # true and false values respectively. # To use the actual value use single or double quotes. -no: no # evaluates to "false": false -yes: No # evaluates to "true": false +no: no # evaluates to "no": false +yes: No # evaluates to "yes": false not_enclosed: yes # evaluates to "not_enclosed": true enclosed: "yes" # evaluates to "enclosed": yes diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown index bac833a6..02f1f7d5 100644 --- a/zh-cn/awk-cn.html.markdown +++ b/zh-cn/awk-cn.html.markdown @@ -179,7 +179,7 @@ function string_functions( localvar, arr) { # 都是返回替换的个数 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" + gsub("e", ".", localvar) # localvar => "M..t m. at th. bar" # 搜索匹配正则的字符串 # index() 也是搜索, 不支持正则 diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index dd4445f7..851f2981 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -474,7 +474,7 @@ void testFunc() { // 用户自定义类型和结构 /////////////////////////////////////// -// Typedefs可以创建类型别名 +// typedef 可以创建类型别名 typedef int my_type; my_type my_type_var = 0; |