How to do it...

  1. Define function types as either internal or external functions. These types can be used as a parameter while calling a function or while returning from a function:
function function_name(<function_type_parameters>)
<internal | external>
<pure | view | payable>
returns (<function_return_types>) {
// ...
}

Internal functions can only be called inside the current contract. External functions can be passed via, and returned from, external function calls. It consists of an address and a function signature.
  1. Create a function that accepts a uint and a function type. Let's call the uint num and the function type fun. For this example, make the function type accept a uint and return a uint:
function calculate (
uint num, // uint type
function (uint) pure returns (uint) fun // function type
) { ... }
  1. Use the received function type to calculate the result and return it:
function calculate (
uint num,
function (uint) pure returns (uint) fun
) internal pure returns (uint r) {
r = fun(num);
}
  1. Create another function that can be passed as a parameter. It should accept a parameter and return a value based on that:
function square(uint x) 
internal pure returns (uint) {
return x * x;
}
  1. This function can be used as a parameter to the calculate function. Let's write another function that invokes the operation:
pragma solidity ^0.4.16;

/**
* Contract which uses function as a type
*/
contract Sample {

function calc(uint num)
public pure returns (uint) {
return calculate(num, square);
}

function square(uint x)
internal pure returns (uint) {
return x * x;
}

function calculate(
uint self,
function (uint) pure returns (uint) f)
internal pure returns (uint r) {
r = f(self);
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.93.169