menu
Menu
Drakon.Tech logo
Drakon.Tech
Open IDE
DocumentationProgramming in DRAKONTutorialsTutorial 1. Hello world!Tutorial 2. Variables and functionsTutorial 3. Basic flow controlTutorial 4. ChoiceTutorial 5. For each loopTutorial 6. The arrow loopTutorial 7. SilhouetteTutorial 8. Lambdas and exceptionsTutorial 9. ModulesTutorial 10. Concurrent programming with scenariosTutorial 11. Working with source controlExamplesLibrariesThe source code

Tutorial 8. Lambdas and exceptions

How create a lambda or a closure

  1. Make a lambda like in the usual JavaScript code.
  2. Don't declare any variables.
A lambda

In a closure, we have access to the outside variables. Here, we read variable a. We will see this when we build and run the project.

18

There is an assignment in the closure lambda. We don't need to put a var keyword there because Drakon.Tech will declare a variable automatically. Keep in mind that the code generator will declare the variable in the containing function, not in the lambda. We can see it in the code.

function lambda() {
    var a, closure, foo, result;
    a = 10
    closure = function (x) {
        foo = a + x
        return foo
    }
    result = closure(8)
    console.log(result)
}

What about other JavaScript statements? Can we use if and for constructs inside lambdas in Drakon.Tech? Technically, it is possible but strongly discouraged. The presence of if and for constructs in a lambda implies an algorithm with nontrivial control flow. Algorithms belong to flowcharts, not to lambdas.

What to do if we must have a complicated algorithm in a lambda?

  1. Move the algorithm in a separate function. Create a DRAKON flowchart for that.
  2. Create a one-line lambda.
  3. Call that new function in the lambda.

Lambdas and closures bring tremendous power, but that power comes at a cost. Every time the reader encounters a lambda in the code, they pay a significant mental price. Keep lambdas as short and straightforward as possible.

How to catch an exception

  1. Make a try-catch construct inside an Action icon like in the usual JavaScript code.
  2. Don't declare any variables.
Catching an exception

All values assigned in a try-catch block will be available later in the function.

Here, the foo variable will keep its value outside of the try-catch block.

close
Close
Drakon.Tech logo
Drakon.Tech home
Programming in DRAKONTutorialsExamplesLibrariesThe source code