Code Preamble
from sympy import symbols,diff,log
from functools import partial
=symbols("x")
x=symbols("b")
b=symbols("y")
y
def call(f, x):
return f(x)
Twotiles is a free and open JavaScript libaray for turning code into visual blocks. The library can be used in any website.
The following uses a simple math example, taking the derivative of a logarithm, to show how code is visualized with the Twotiles library.
from sympy import symbols,diff,log
from functools import partial
=symbols("x")
x=symbols("b")
b=symbols("y")
y
def call(f, x):
return f(x)
Using SymPy, one can calculate with symbols. Here, x
is a symbol.
5/x - (50 + 14)
\(\displaystyle -64 + \frac{5}{x}\)
64.0) log(
\(\displaystyle 4.15888308335967\)
One can also make an explicit call to the log
function.
64.0) call(log,
\(\displaystyle 4.15888308335967\)
This makes call
a special kind of function. Because it takes a function as its first argument, call
is a function of “higher order”. But for now we return to the usual way of making a calculation.
* 5) log(x
\(\displaystyle \log{\left(5 x \right)}\)
* 5, x) diff(log(x)
\(\displaystyle \frac{5}{x}\)
diff(log(x),x)
\(\displaystyle \frac{1}{x}\)
def logarithm(b, x):
return log(x) / log(b)
8.0, 64.0) logarithm(
\(\displaystyle 2.0\)
def log_base(b):
return partial(logarithm, b)
8.0),64.0) call(log_base(
\(\displaystyle 2.0\)
8.0),x),x) diff(call(log_base(
\(\displaystyle \frac{0.480898346962988}{x}\)
to_infix(
call(diff(log_base(8.0)), x)
)
to_infix(
call(diff(log), x)
)
To display graphical blocks, include into your web-site the Scittle, Blockly and indeed the Twotiles library:
<script src="https://cdn.jsdelivr.net/npm/scittle@0.6.22/dist/scittle.js"></script>
<script src="https://unpkg.com/blockly/blockly.min.js"></script>
<script src="https://unpkg.com/blockly/msg/en.js"></script>
<script src="https://kloimhardt.github.io/twotiles/twotiles_core.js"></script>
Then initialize the Twotiles parser …
<script>
var parse = scittle.core.eval_string(twotiles.parse_clj);
</script>
… and Blockly:
<script>
Blockly.defineBlocksWithJsonArray(twotiles.blocks);
</script>
It is convenient to have a render function:
<script>
var brender = (code,divid) =>
Blockly.Xml.clearWorkspaceAndLoadFromXml(Blockly.utils.xml.textToDom(parse(code)),
Blockly.inject(divid,
{"toolbox": twotiles.toolbox,
"sounds": false,
"scrollbars": false,
"trashcan": false}));
</script>
Then graphics can be displayed with
<div id="blocklyDiv" style="height: 100px;"></div>
<script>brender("(log 64)", "blocklyDiv")</script>
which looks like this:
A detailed example of EmmyJS can be found at sicmutils-as-js-book-part1.html
This page was generated with Quarto out of the file twotiles.qmd