>>>>> "Scott" == Scott Brown <[email protected]> writes:
Scott> I have started learning Factor and after trying out the
Scott> palindrome tutorial, I am now trying to make a simple program for
Scott> filtering out non-prime numbers from a list.
Scott> I have made a word multiple-of? which returns true if x is a
Scott> multiple of y.
Scott> : multiple-of? ( x y -- ? ) [ = not ] [ mod 0 = ] 2bi and ;
Scott> I would like to use it filter a sequence of numbers like the
Scott> expression below, but looping through each of the numbers in the
Scott> sequence to remove its multiples, leaving only prime numbers.
Scott> { 2 3 4 5 6 7 8 9 10 } [ 2 multiple-of? not ] filter
Scott> Is there some loop or combinator that I could use to do this in
Scott> Factor?
You can apply the filtering process with every number instead of just
2 by using `curry'. This word lets you "insert" an element into a
quotation.
For example,
2 [ multiple-of? not ] curry
is equivalent to
[ 2 multiple-of? not ]
This way, you can build the quotation to give to filter for every number
in the list by iterating with "each":
{ 2 3 4 5 6 7 8 9 10 } dup [ [ multiple-of? not ] curry filter ] each
You can check that it works as expected by using a longer list, from 2
to 50 for example:
USE: math.ranges
2 50 [a,b] dup [ [ multiple-of? not ] curry filter ] each
=> V{ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 }
As a side note, you can obtain prime numbers more easily:
USE: math.primes
50 primes-upto
=> V{ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 }
Sam
--
Samuel Tardieu -- [email protected] -- http://www.rfc1149.net/
------------------------------------------------------------------------------
Come build with us! The BlackBerry® Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay
ahead of the curve. Join us from November 9-12, 2009. Register now!
http://p.sf.net/sfu/devconf
_______________________________________________
Factor-talk mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/factor-talk