Skip to content

Declaring and calling inner functions sample

CodingUnit edited this page Oct 24, 2011 · 9 revisions

Declaring and calling inner functions

  • Category: Functions
  • Description: Declaring and calling functions within the body of another function
  • Code:
using System.Console;


 def FunctionSample2()
 {
    def even(n) { n % 2 == 0 }
    def tick(x) { WriteLine($"tick $x") }
    def tock(x) { WriteLine($"tock $x") }
    
    def choose(f, g, h, x) { if (f(x)) g(x) else h(x) }
    def ticktock = choose(even, tick, tock, _);  // ticktock is a function built out of other functions using 'choose'
    for (mutable i = 0; i < 10; ++i)     
       ticktock(i);    
}

FunctionSample2();

Execution Result:

tick 0
tock 1
tick 2
tock 3
tick 4
tock 5
tick 6
tock 7
tick 8
tock 9
tick 10

Clone this wiki locally