[OpenSCAD] Functions literals / higher order functions

Michael Marx michael at marx.id.au
Tue Nov 26 07:08:39 EST 2019


Not normal scope, a bug in how it works.

 

function move(a, g) = echo(move=a,g)

  function(m) 

      echo(m_in_move=a,m,g)

      assert(m<12)

        g(echo(str("call g(",m+a,")[g=",g,"]")) m+a) ;

 

g1 = function(x)

       echo(fx=x)

          x;

g2 = move(2,g1);

g3 = move(3,g2);

 

echo(g2_=g2);

echo(g3_x=g3);

echo(g3_5=g3(5));

 

Produces

 

Compiling design (CSG Tree generation)...

ECHO: move = 2, function(x) echo(fx = x) x

ECHO: move = 3, function(m) echo(m_in_move = a, m, g) assert((m 

ECHO: g2_ = function(m) echo(m_in_move = a, m, g) assert((m 

ECHO: g3_x = function(m) echo(m_in_move = a, m, g) assert((m 

ECHO: m_in_move = 3, 5, function(m) echo(m_in_move = a, m, g) assert((m 

ECHO: "call g(8)[g=function(m) echo(m_in_move = a, m, g) assert((m 

ECHO: "call g(8)[g=function(m) echo(m_in_move = a, m, g) assert((m 

ECHO: m_in_move = 2, 8, function(x) echo(fx = x) x

ECHO: "call g(10)[g=function(x) echo(fx = x) x]"

ECHO: m_in_move = 2, 10, function(x) echo(fx = x) x

ECHO: "call g(12)[g=function(x) echo(fx = x) x]"

ECHO: m_in_move = 2, 12, function(x) echo(fx = x) x

ERROR: Assertion '(m < 12)' failed in file fn literals ronaldo.scad, line 4

TRACE: called by 'g', in file fn literals ronaldo.scad, line 5.

TRACE: called by 'g3', in file fn literals ronaldo.scad, line 15.

TRACE: called by 'echo', in file fn literals ronaldo.scad, line 15.

Compiling design (CSG Products generation)...

Geometries in cache: 0

 

You can see it is saying it wants to call g1, but is actually calling g2 recursively.

 

  _____  

From: Discuss [mailto:discuss-bounces at lists.openscad.org] On Behalf Of Ronaldo Persiano
Sent: Tue, 26 Nov 2019 22:58
To: OpenSCAD general discussion
Subject: Re: [OpenSCAD] Functions literals / higher order functions

 

Yet another hack that works:

 

function move(a, g) =
   function(x)
     let( v = g(x+a) ) v;

g1 = function(x) x;
g2 = move(2, g1);
g3 = move(3, g2);

echo(g3_x=g3);

echo(g3_2=g3(2));

 

Compiling design (CSG Tree generation)...

ECHO: g3_x = function(x) let(v = g((x + a))) v

ECHO: g3_2 = 7

Compiling design (CSG Products generation)...

Geometries in cache: 1

Geometry cache size in bytes: 270008

CGAL Polyhedrons in cache: 0

CGAL cache size in bytes: 0

Compiling design (CSG Products normalization)...

Normalized CSG tree has 0 elements

Compile and preview finished.

 

I can't see how scope may matter here.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openscad.org/pipermail/discuss_lists.openscad.org/attachments/20191126/cf5c2149/attachment.html>


More information about the Discuss mailing list