Re: Factor

Factor: the language, the theory, and the practice.

ASCII Art

Friday, September 8, 2023

#math

Raymond Hettinger, an active contributor to Python and responsible for many useful improvements to the language, likes to tweet short and sweet bits of useful Python knowledge. I stumbled into one fun one-liner from long ago:

I thought I would show how it might translate into Factor. To translate this code into a concatenative language, we are going to work from the inside and move out.

Step 1

We start with the sum of the cartesian product of eight sequences of the numbers 0 through 5:

map(sum, product(range(6), repeat=8))

vs.

8 6 <iota> <repetition> [ sum ] product-map

Step 2

Next, we see that it counts each element, and produces a sorted list of items:

sorted(Counter(...).items())

vs.

histogram sort-keys

Step 3

And finally, create a string of lines of stars and print it:

print "\n".join('*'*(c//2000) for i,c in ...)

vs.

values [ 2000 /i CHAR: * <string> ] map "\n" join print

Solution

Putting it all together:

IN: scratchpad USING: assocs io math math.statistics sequences
               sequences.product sorting strings ;

IN: scratchpad 8 6 <iota> <repetition> [ sum ] product-map
               histogram sort-keys values
               [ 2000 /i CHAR: * <string> ] map "\n" join print

It makes this nice ASCII Art visualization:

*
***
*****
********
************
******************
*************************
********************************
*****************************************
*************************************************
********************************************************
**************************************************************
******************************************************************
*******************************************************************
******************************************************************
**************************************************************
********************************************************
*************************************************
*****************************************
********************************
*************************
******************
************
********
*****
***
*