Factorial in APL

Example for versions Dyalog APL 13.1

The first line sets the index of the first element in the lists (in this case 0). The second line sets precision when printing numbers (must be greater than the length of the largest factorial).

The third line, if read in right-to-left direction, performs the following operations:

  • ⍳17 generates a list of 17 indices, starting with 0, i.e. 0 … 16.

  • 17 / ⊂'!=' generates a list of 17 strings !=. is enclose operator which allows to manipulate strings as scalars instead of character arrays. / is replication operator.

  • !⍳17 applies built-in monadic function ! (factorial) to each element of the list.

  • , is a dyadic operation which concatenates left and right arguments. After two concatenations the expression evaluates to 0 1 2 3 4 ... 15 16 != != ... != 1 1 2 6 24 120 720 5040 40320 362880 ..., i.e. the list of numbers followed by the list of strings and the list of factorials.

  • 3 17⍴ reshapes the list into a 3x17 matrix:

    ┌→─┬──┬──┬──┬──┬───┬───┬────┬─────┬──────┬───────┬────────┬─────────┬──────────┬───────────┬─────────────┬──────────────┐  
    ↓0 │1 │2 │3 │4 │5  │6  │7   │8    │9     │10     │11      │12       │13        │14         │15           │16            │  
    ├~─┼~─┼~─┼~─┼~─┼~──┼~──┼~───┼~────┼~─────┼~──────┼~───────┼~────────┼~─────────┼~──────────┼~────────────┼~─────────────┤  
    │!=│!=│!=│!=│!=│!= │!= │!=  │!=   │!=    │!=     │!=      │!=       │!=        │!=         │!=           │!=            │  
    ├─→┼─→┼─→┼─→┼─→┼──→┼──→┼───→┼────→┼─────→┼──────→┼───────→┼────────→┼─────────→┼──────────→┼────────────→┼─────────────→┤  
    │1 │1 │2 │6 │24│120│720│5040│40320│362880│3628800│39916800│479001600│6227020800│87178291200│1307674368000│20922789888000│  
    └~─┴~─┴~─┴~─┴~─┴~──┴~──┴~───┴~────┴~─────┴~──────┴~───────┴~────────┴~─────────┴~──────────┴~────────────┴~─────────────┘
    
  • finally, transposes this matrix so that each row has three elements — a number, a separator string and a factorial.

The program output looks like this:

     ┌→─┬──┬──────────────┐          
     ↓0 │!=│1             │          
     ├~─┼─→┼~─────────────┤          
     │1 │!=│1             │          
     ├~─┼─→┼~─────────────┤          
     │2 │!=│2             │          
     ├~─┼─→┼~─────────────┤          
     [...25 lines of output ...]  
     ├~─┼─→┼~─────────────┤          
     │16│!=│20922789888000│          
     └~─┴─→┴~─────────────┘

The matrix is displayed as a table with cell borders drawn, because it contains boxed strings.

IO0
PP18
3 17 (17) , (17 / '!=') , !17