How do I construct functional and recursive datatypes in javascript?
I would like to be able to do something ML like:
datatype binary_node = Node of binary_node*binary_node
| Lead of int
Some time ago I took a course in functional programming — the course was, for some random reason, in Scheme, and we constructed datatypes by making tubles, starting with the name of the data type and then the ‘payload’, is this the way to do functional programming-style data types in Javascript?
construct_node(n1,n2) ->
("Node", n1, n2).
construct_leaf(int_value) ->
("Leaf", int_value).
and then a type checker:
is_node(n) ->
if (n[0] == "Node") ->
is_binary_tree(n[1]) and is_binary_tree(n[2])
else
false
is_leaf(l) ->
if(l[0] == "Leaf") ->
is_integer(n[1])
else
false
is_binary_tree(t) ->
is_node(t) or is_leaf(t)
What would be the smartest way to do this in javascript?
JavaScript is commonly used in a duck typed fashion. In this way, you don’t need to define any special datatypes. Any object that has properties
node1andnode2may be considered a binary tree node.Note that the functions above are for recursively checking the integrity of an entire tree, not for node-by-node case distinction during traversal.