aboutsummaryrefslogtreecommitdiffstats
path: root/docs/types.rst
diff options
context:
space:
mode:
authorchriseth <c@ethdev.com>2016-10-27 00:01:08 +0800
committerchriseth <c@ethdev.com>2016-11-16 21:37:18 +0800
commit502cc319d79c28cf398baa737e96c54563b9aafa (patch)
treeee606964604e7ab65b91b1d9b1e28fa55be51496 /docs/types.rst
parent87b148494bcf1dd4814fafe658dd81fef79cf8b4 (diff)
downloaddexon-solidity-502cc319d79c28cf398baa737e96c54563b9aafa.tar.gz
dexon-solidity-502cc319d79c28cf398baa737e96c54563b9aafa.tar.zst
dexon-solidity-502cc319d79c28cf398baa737e96c54563b9aafa.zip
Documentation examples.
Diffstat (limited to 'docs/types.rst')
-rw-r--r--docs/types.rst74
1 files changed, 73 insertions, 1 deletions
diff --git a/docs/types.rst b/docs/types.rst
index 2e1cbee9..cac8b774 100644
--- a/docs/types.rst
+++ b/docs/types.rst
@@ -302,10 +302,82 @@ in an exception.
If external function types are used outside of the context of Solidity,
they are converted into the ``bytes24`` type.
-Example usage:
+Example that shows how to use internal function types:
library ArrayUtils {
+ // internal functions can be used in internal library functions because
+ // they will be part of the same code context
+ function map(uint[] memory self, function (uint) returns (uint) f)
+ returns (uint[] memory r)
+ {
+ r = new uint[](self.length);
+ for (uint i = 0; i < self.length; i++) {
+ r[i] = f(self[i]);
+ }
+ }
+ function reduce(
+ uint[] memory self,
+ function (uint) returns (uint) f
+ )
+ returns (uint r)
+ {
+ r = self[0];
+ for (uint i = 1; i < self.length; i++) {
+ r = f(r, self[i]);
+ }
+ }
+ function range(uint length) returns (uint[] memory r) {
+ r = new uint[](length);
+ for (uint i = 0; i < r.length; i++) {
+ r[i] = i;
+ }
+ }
+ }
+ contract Pyramid {
+ using ArrayUtils for *;
+ function pyramid(uint l) return (uint) {
+ return ArrayUtils.range(l).map(square).reduce(sum);
+ }
+ function square(uint x) internal returns (uint) {
+ return x * x;
+ }
+ function sum(uint x, uint y) internal returns (uint) {
+ return x + y;
+ }
+ }
+
+Another example that uses external function types:
+
+ contract Oracle {
+ struct Request {
+ bytes data;
+ function(bytes) external callback;
+ }
+ Request[] requests;
+ event NewRequest(uint);
+ function query(bytes data, function(bytes) external callback) {
+ requests.push(Request(data, callback));
+ NewRequest(requests.length - 1);
+ }
+ function reply(uint requestID, bytes response) {
+ // Here goes the check that the reply comes from a trusted source
+ requests[requestID].callback(response);
+ }
+ }
+
+ contract OracleUser {
+ Oracle constant oracle = 0x1234567; // known contract
+ function buySomething() {
+ oracle.query("USD", oracleResponse);
+ }
+ function oracleResponse(bytes response) {
+ if (msg.sender != oracle) throw;
+ // Use the data
+ }
+ }
+
+Note that lambda or inline functions are planned but not yet supported.
.. index:: ! type;reference, ! reference type, storage, memory, location, array, struct