Dynamic functions over an abstract function, with and without captures
The complete source of dynamicFunctions_math.ek9, compiled by the EK9 compiler. Shown on dynamicFunctions.html.
#!ek9 defines module site.dynamicFunctions.math defines function mathOperation() as pure abstract -> x as Float y as Float <- result as Float? defines program DynamicMathExample1() stdout <- Stdout() stdout.println("Math Dynamic Operation Example1") fixedValue <- 9.8 // is/extends and 'as function' are just syntactic sugar, examples of each // notice how the incoming and returning parameter names are inferred from mathOperation addFunction <- () is mathOperation as pure function result: x+y subtractFunction <- () extends mathOperation as pure result: x-y divideFunction <- () is mathOperation pure result: x/y multiplyFunction <- () is mathOperation pure result: x*y specialFunction <- (fixedValue) is mathOperation pure result: (x+fixedValue) * y^fixedValue // common super of mathOperation is inferred and ops is a 'List of mathOperation' ops <- [addFunction, subtractFunction, divideFunction, multiplyFunction, specialFunction] for op in ops stdout.println(`Result: ${op(21, 7)}`) DynamicMathExample2() stdout <- Stdout() stdout.println("Math Dynamic Operation Example2") fixedValue <- 9.8 //Nearest EK9 gets to a lambda - wrap in parenthesis on single line. //Notice the last entry - 'captures' fixedValue and can use it in the function body ops <- [ () is mathOperation as pure (result: x+y), () is mathOperation as pure (result: x-y), () is mathOperation as pure (result: x/y), () is mathOperation as pure (result: x*y), (fixedValue) is mathOperation pure (result: (x+fixedValue) * y^fixedValue) ] for op in ops stdout.println(`Result: ${op(21, 7)}`) DynamicMathExample3() stdout <- Stdout() stdout.println("Math Dynamic Operation Example3") fixedValue <- 9.8 //Same example but uses an inline list in the for loop. for op in [ () is mathOperation as pure (result: x+y), () is mathOperation as pure (result: x-y), () is mathOperation as pure (result: x/y), () is mathOperation as pure (result: x*y), (fixedValue) is mathOperation pure (result: (x+fixedValue) * y^fixedValue) ] stdout.println(`Result: ${op(21, 7)}`)
Download dynamicFunctions_math.ek9
Output
DynamicMathExample1
Math Dynamic Operation Example1 Result: 28.0 Result: 14.0 Result: 3.0 Result: 147.0 Result: 5.895375993827891E9
DynamicMathExample2
Math Dynamic Operation Example2 Result: 28.0 Result: 14.0 Result: 3.0 Result: 147.0 Result: 5.895375993827891E9
DynamicMathExample3
Math Dynamic Operation Example3 Result: 28.0 Result: 14.0 Result: 3.0 Result: 147.0 Result: 5.895375993827891E9