BQN functions and factorization
Disclaimer: I am still a beginner and I may write incorrect things.
In BQN you either define a function as tacit or explicitly within blocks. I mostly code using blocks {}
because it is easier to program than tacitly.
But once I finish writing my functions, I try to factorize them and, even better, to make them tacit.
In BQN you only have a right argument and sometime a left argument, not more. This allow us to factorize the code. For example, if we are in a situation like {π© π½ πΎ π©}
we use the before operator β
to remove the duplication of $π©$ (and make it tacit!): π½βπΎ
.
The way I program in BQN is to first write my functions as simple as possible with lot of π© and π¨ and way too much parenthesis. Then, I draw a diagram like the following where I represent the operations order.
Finally, I factorize my code by finding patterns in the graph. In this case we get π½βπΎ
.
Here is an example a bit more complex, I drew this one when I coded my planner.
This factorization uses a train which is something I never saw before beginning array programming language.
I am still too inexperienced to know if factorizing everything is a good idea or not. On one hand, it creates a lot of overhead when reading code as the information density is very high but, on the other hand, maybe it is like math where after months of reading the same factorization pattern we just automatically infer the meaning just by looking at it. If it is the latter then it would be very beneficial for me to factor everything I could.
Anyway, here are some patterns and their factorizations. I made this as a cheatsheet for me and other BQN programmers.
So now, a little example. Let’s say you want to compute the projection of a 2D $p$ point into a line defined by a vector $v$. The formula is $$p’ = (p . \frac{v}{||v||})\frac{v}{||v||}$$
And if we draw the operation diagram it would look like this:
Let’s define the dot product as DotProd
and the normalization as Normalize
and we get (DotProd Γ β’)βNormalize
. Of course, in this example it would have been easier to write directly the primitives instead of creating functions.
What I talked today in this post could certainly be automated. I can imagine an editor extension that factorize an expression or develop it to the level the user want. I personally use emacs and my emacs-lisp is not good enough to tackle the challenge but I hope someday somebody will!