JS for functional programming? 
Author Message
 JS for functional programming?



Quote:

> Has anyone ever explored the idea of using JS (pure) as a language for
> functional programming?  It seems ideally suited to me but I'm not an
> expert in FP.

I'm not an expert in either functional programming or
JavaScript.  But here's my take: functions are first-class
objects in JS--they can be passed to, returned from, or
created by a function, and can be bound to variables.
JS supports recursion and has garbage collection.  What
more do you need?  After writing the code below, I'd say
nothing.  However, I wouldn't use the word "ideal", as
the syntax gets a little awkward compared to say, Haskell.

I welcome comments on either the JavaScript or functional
programming aspects of the following.

/**
* Functional programming in JavaScript
*/

/**
* This was developed on Windows Scripting Host.  To use
* on other environments change WScript.echo() to whatever
* displays a string on the console.
*/
function trace(str) {WScript.echo(str + " -> " + eval(str))}
trace("2 + 2")

/**
* Given a number n, returns a string of the form
* '"a1", "a2", ..., "an"'.
*
* Useful in constructing functions because the runtime won't
* allow changing a function's length property (number of
* arguments expected) after the function has been created.
*/
function make_formal_arg_list(n) {
   if (0 == n) {
      return ""
   }
   return make_formal_arg_list(n - 1) + "\"a" + n + "\","

Quote:
}

trace("make_formal_arg_list(0)")
trace("make_formal_arg_list(3)")

/**
* Given a number n, returns a string of the form
* ", arguments[0], arguments[1], ..., arguments[n-1]".
*
* What is really needed is a way to call a function with
* a program generated argument array (like apply but
* without the "thisArg" parameter.)
*/
function make_actual_arg_list(n) {
   if (0 == n) {
      return ""
   }
   var n_1 = n - 1
   return make_actual_arg_list(n_1) + ", arguments[" + (n_1) + "]"

Quote:
}

trace("make_actual_arg_list(0)")
trace("make_actual_arg_list(3)")

/**
* Given a function f of n arguments, and an argument a1,
* returns a new function g of n-1 arguments such that
* f(a1, a2, ..., an) == g(a2, ..., an).
*/
function bind1st(f, a) {
   var num_args = f.length - 1
   var g = eval("new Function(" + make_formal_arg_list(num_args)
      + "\"return arguments.callee.f(arguments.callee.a"
      + make_actual_arg_list(num_args) + ")\")")
   g.f = f
   g.a = a
   return g

Quote:
}

function add(x, y) {return x + y}
var succ = bind1st(add, 1)
trace("succ(succ(40))")

/**
* Given a function f of n arguments, returns a new function g
* of 1 argument such that f(a1, a2, ..., an) == g(a1)(a2)...(an).
*/
function curry(f) {
   if (f.length < 2) {
      return f
   }
   else
   {
      var g = new Function("a1",
         "return curry(bind1st(arguments.callee.f, arguments[0]))")
      g.f = f
      return g
   }

Quote:
}

function triplet(a, b, c) {return [a, b, c]}
trace("triplet('X', 'Y', 'Z')")
trace("curry(triplet)('A')('B')('C')")

/**
* Given a 2 argument function, returns a new function g,
* such that f(x,y) == g(y, x).
*/
function flip(f) {
   var g = eval("new Function(" + make_formal_arg_list(2)
      + "\"return arguments.callee.f(arguments[1], arguments[0])\")")
   g.f = f
   return g

Quote:
}

function minus(x, y) {return x - y}
var pred = curry(flip(minus))(1)
trace("pred(pred(44))")

/**
* Given 1-argument functions f and g, returns a new function h,
* such that f(g(x)) == h(x).
*/
function compose(f, g) {
   var h = new Function("x",
      "return arguments.callee.f(arguments.callee.g(arguments[0]))")
   h.f = f
   h.g = g
   return h

Quote:
}

var two_to_the = curry(Math.pow)(2)
trace("two_to_the(8)")
trace("compose(two_to_the, pred)(8)")
trace("compose(pred, two_to_the)(8)")

Sent via Deja.com
http://www.*-*-*.com/



Sat, 19 Jul 2003 17:49:07 GMT  
 JS for functional programming?

Quote:

> /**
> * Functional programming in JavaScript
> */

I can't resist but mention: as a joke, I've written a simple
scheme-like interpreter in Javascript.

I've now put it on the web. The interpreter source code is at
http://www.bluetail.com/~luke/jscm/scm.js.txt and you can download it
with examples from http://www.bluetail.com/~luke/downloads/jscm.tar.gz
- just unpack, run 'make', and then load test.html in your browser
(and don't be worried that most of the examples have no output).

It's my first javascript program so it's probably in an unconventional
style. Also I wasn't sure exactly how to implement some scheme
features (e.g. macros and quasiquote) so they're a bit quirky - but it
should be complete enough to get some fun out of.

Cheers,
Luke



Sat, 19 Jul 2003 18:51:29 GMT  
 JS for functional programming?

 | I'm not an expert in either functional programming or
 | JavaScript.  But here's my take: functions are
 | first-class objects in JS--they can be passed to,
 | returned from, or created by a function, and can be
 | bound to variables.

As in many scripting languages, these objects/functions are
all represented as strings by JavaScript. (JavaScript adds
an extra convenient layer of objects, which basically are
lookup tables from strings to strings).

To my knowledge, this makes it impossible to garbage collect
anything, since one can always dynamically recreate the name
of any object/function as a string, after having lost the
name.

In your example, when you create the local function in
`flip', it can never be garbage collected.

Am I right on this?

/Koen.

--
Koen Claessen         http://www.cs.chalmers.se/~koen

-----------------------------------------------------
Chalmers University of Technology, Gothenburg, Sweden



Sat, 19 Jul 2003 19:02:25 GMT  
 JS for functional programming?

Quote:

> As in many scripting languages, these objects/functions are
> all represented as strings by JavaScript. [...]

> To my knowledge, this makes it impossible to garbage collect
> anything, since one can always dynamically recreate the name
> of any object/function as a string, after having lost the
> name.

> In your example, when you create the local function in
> `flip', it can never be garbage collected.

> Am I right on this?

I don't believe so.  The Function constructor creates a new function
object but does not associate the object with any lookup tables (i.e.,
the object is not stored in a property of an object in the present scope
chain).  As a result, an expression like

    new Function( ... )

creates an object that can be immediately reclaimed by the garbage
collector, unless the object is captured:

    var g = new Function( ... )

Even captured, the function object can be reclaimed when execution
leaves the execution context in which the capturing property is stored.
For example, consider this trivial function:

    function test() {
        var g = new Function( ... )
    }

When the function `test' exits, g is reclaimed (i.e., the activation
object associated with this call of test is reclaimed, and g goes with
it), removing the last reference to the new function object.  The
function object is then free to be reclaimed by the garbage collector.

See the ECMA-262 specification for more on this:

    ftp://ftp.ecma.ch/ecma-st/Ecma-262.pdf

Cheers,
Tom



Sun, 20 Jul 2003 01:21:31 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. JS for functional programming?

2. JS-EAI with *JS*-callback

3. js.exception 3279.js

4. functional.py 0.6 - Functional Programming in Python

5. functional.py 0.7 - Functional programming in Python

6. functional.py - functional programming in Python

7. functional.py 0.7 - Functional programming in Python

8. functional.py 0.6 - Functional Programming in Python

9. functional.py - functional programming in Python

10. US PhD programs strong on functional programming?

11. ICFP Functional Programming Contest

12. ICFP functional programming contest -- deadline correction

 

 
Powered by phpBB® Forum Software