File: echo.scad

package info (click to toggle)
openscad 2021.01-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 36,012 kB
  • sloc: cpp: 53,199; sh: 4,384; ansic: 4,382; python: 1,813; yacc: 853; javascript: 762; lex: 417; lisp: 163; xml: 127; makefile: 118
file content (48 lines) | stat: -rw-r--r-- 1,723 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
echo(version=version());

// Using echo() in expression context can help with debugging
// recursive functions. See console window for output of the
// examples below.

// Simple example just outputting the function input parameters.
function f1(x, y) = echo("f1: ", x, y) 0.5 * x * x + 4 * y + 1;

r1 = f1(3, 5);

// To output the result, there are multiple possibilities, the
// easiest is to use let() to assign the result to a variable
// (y here) which is used for both echo() output and result.
function f2(x) = let(y = pow(x, 3)) echo("f2: ", y) y;

r2 = f2(4);

// Another option is using a helper function where the argument
// is evaluated first and then passed to the result() helper
// where it's printed using echo() and returned as result.
function result(x) = echo("f3: ", x) x;
function f3(x) = result(x * x - 5);

r3 = f3(5);

// A more complex example is a recursive function. Combining
// the two different ways of printing values before and after
// evaluation it's possible to output the input value x when
// descending into the recursion and the result y collected
// when returning.
function f4(x) = echo("f4: ", x = x)
                 let(y = x == 1 ? 1 : x * f4(x - 1))
                 echo("f4: ", y = y)
                 y;

r4 = f4(5);

// Written in 2018 by Torsten Paul <Torsten.Paul@gmx.de>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to the
// public domain worldwide. This software is distributed without any
// warranty.
//
// You should have received a copy of the CC0 Public Domain
// Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.