Category:Factor-numspec

From Rosetta Code
Revision as of 20:52, 24 July 2021 by Chunes (talk | contribs) (Add Factor-numspec library/vocabulary)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Library
This is an example of a library. You may see a list of other libraries used on Rosetta Code at Category:Solutions by Library.

Factor-numspec is a vocabulary that aims to make tasks involving the restriction of digits within numbers easy. This vocabulary was made because there are a fair number of tasks on Rosetta Code involving this operation and more being added all the time.

To use it yourself, copy the source code (in the talk page) to a text file called numspec.factor and then save it in a sub-directory called numspec inside your work directory. work is in the same directory as the Factor executable.

Finally, in your program, make sure to add numspec to your USING: like so:

<lang factor>USING: math numspec prettyprint ;</lang>

Examples

It's important to remember that a number specification creates a lazy list of integers. Whether the list ends or not depends on whether you end the specification with ... or not.

Get all three-digit numbers beginning and ending with 3: <lang factor>USING: lists numspec prettyprint ; NUMSPEC: 3_3 ; list>array .</lang>

Output:
{ 303 313 323 333 343 353 363 373 383 393 }

Literals can be added where necessary. Let's make special cases for one- and two-digit numbers. <lang factor>USING: lists numspec prettyprint ; NUMSPEC: 3 33 3_3 ; list>array .</lang>

Output:
{ 3 33 303 313 323 333 343 353 363 373 383 393 }

But what if you don't want to make a case for every number of digits? Got you covered! ... rudimentarily infers the pattern. <lang factor>USING: lists lists.lazy numspec prettyprint ; NUMSPEC: 3 33 3_3 ... ; [ 3030 < ] lwhile list>array .</lang>

Output:
{ 3 33 303 313 323 333 343 353 363 373 383 393 3003 3013 3023 }

Since this is an infinite list, we need to remember to limit it in some fashion (like with lwhile).

numspec comes with symbols for common digit restrictions. Let's get a list of the numbers with prime digits. <lang factor>USING: lists lists.lazy numspec prettyprint ; 20 NUMSPEC: P PP ... ; ltake list>array .</lang>

Output:
{ 2 3 5 7 22 23 25 27 32 33 35 37 52 53 55 57 72 73 75 77 }

Adding your own digit restrictions is easy. Just define a 1-character constant as a list with the possibilities. <lang factor>USING: lists lists.lazy numspec prettyprint ; CONSTANT: V L{ 2 5 } NUMSPEC: 9 99 9V9 ... ; 30 swap ltake list>array .</lang>

Output:
{
    9
    99
    929
    959
    9229
    9259
    9529
    9559
    92229
    92259
    92529
    92559
    95229
    95259
    95529
    95559
    922229
    922259
    922529
    922559
    925229
    925259
    925529
    925559
    952229
    952259
    952529
    952559
    955229
    955259
}

Pages in category "Factor-numspec"

The following 2 pages are in this category, out of 2 total.