mirror of
https://github.com/ethereum/solidity
synced 2023-10-03 13:03:40 +00:00
Documentation examples.
This commit is contained in:
parent
87b148494b
commit
502cc319d7
@ -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
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user