Subscribe Bookmark RSS Feed

Functional Programming with JSL, Anyone?

Highlighted
ih

Community Trekker

Joined:

Sep 30, 2016

Does anyone write JSL using functional programming, and if so do you have a standard set of functions that you use?

 

As an example, the simplified map function below does all of the work of a for loop so you only need to specify an expression and a list and the function returns a list with the function evaluted for each element. In R, a similar function and variants of it can be found in the package 'purrr' by Lionel Henry and Hadley Wickham.

 

// A function to evaluate an expression for each item in a list
// 
// x__   A list
// fn__  An expression containing ___ (three underscores) that
//       is replaced with each element of x__
//
// Returns a list the same length as x__.
//
map = function( {x__, fn__},
	r__ = {};
	for(i__ = 1, i__ <= N items( x__ ), i__++,
		r__ = Insert( r__, Eval( substitute(Name Expr( fn__ ), Expr(___), Expr( x__[i__] ) ) ) );
	);
	return(r__);
);

//Data to evaluate
vals = { 1, 2, 3, -3, -2, 0.5, -1.1, 5.3, 2.7, 0 };

//number of entries above zero
map( vals, Expr( ___ > 0 ) ); 

//sum of fractional parts
sum( map( vals, Expr( Mod( ___, 1 ) ) ) );