From OCaml to Javascript

J

Jon Harrop

I'm trying to grok Javascript. As my background is functional programming
languages, all the higher-order functions, currying and so forth are easy
but I've no idea how to express sum types and pattern matches.

Is there a resource to teach the (tiny minority!) of people like me
Javascript?

How do you translate the following symbolic simplifier into Javascript, for
example:

http://www.codecodex.com/wiki/index.php?title=Derivative
 
T

Thomas 'PointedEars' Lahn

Jon said:
I'm trying to grok Javascript. As my background is functional programming
languages, all the higher-order functions, currying and so forth are easy
but I've no idea how to express sum types and pattern matches.

This may surprise you, but ECMAScript implementations include features of
functional languages.

http://javascript.crockford.com/javascript.html
Is there a resource to teach the (tiny minority!) of people like me
Javascript?

This newsgroup? Maybe one of the many resources linked in its FAQ?
How do you translate the following symbolic simplifier into Javascript, for
example:

http://www.codecodex.com/wiki/index.php?title=Derivative

I don't know yet, but please tell us when you got it.


PointedEars
 
J

Jon Harrop

Thomas said:
I don't know yet, but please tell us when you got it.

I think I've made some progress. If you take the minimal OCaml example:

# let rec ( +: ) f g = match f, g with
| `Int 0, f | f, `Int 0 -> f
| f, `Add(g, h) -> f +: g +: h
| f, g -> `Add(f, g);;
val ( +: ) : ([> `Add of 'a * 'a | `Int of int ] as 'a) -> 'a -> 'a = <fun>

Then the polymorphic variant type that OCaml inferred is equivalent to a
class hierarchy in JavaScript, which must be something like:

// Equivalent to `Add
function Add(f, g) {
this.f = f;
this.g = g;
}

// Equivalent to +:
function add(f, g) {
if f=0 then g else
if g=0 then f else
if g instanceOf Add then add(add(f, g.f), g.g) else
Add(f, g)
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top