Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Filtering

74 views
Skip to first unread message

WJ

unread,
Mar 2, 2013, 2:48:43 AM3/2/13
to
Given a sequence of numbers, keep those that are odd and
multiply them by 100.

Factor:


USE: sequences.extras

{ 1 1 2 3 5 8 13 21 } [ odd? ] [ 100 * ] filter-map
{ 100 100 300 500 1300 2100 }

Marcel Hendrix

unread,
Mar 2, 2013, 4:17:16 AM3/2/13
to
"WJ" <w_a_...@yahoo.com> writes Re: Filtering
8 integer array x{ 1 1 2 3 5 8 13 21 x{ #=>
: fm ( x -- ) dup cdim 0 ?do dup i } @ dup 1 and if 100 * . else drop endif loop drop ;

x{ fm 100 100 300 500 1300 2100 ok

Or:

: fm BEGIN bl word dup C@
WHILE count evaluate dup 1 and IF 100 * . ELSE drop ENDIF
REPEAT drop ;

FORTH> fm 1 1 2 3 5 8 13 21 100 100 300 500 1300 2100 ok
FORTH> hex fm 1 f 2e 333 331 21fe 64 5DC 13FEC 13F24 ok
FORTH> fm %01 %1 #10 %11 %1001 %1000 #13 $15 100 100 300 900 1300 2100 ok

-marcel

Charles Childers

unread,
Mar 2, 2013, 11:18:40 AM3/2/13
to
Parable:

[ #1 #1 #2 #3 #5 #8 #13 #21 ] array-from-quote
[ odd? ] array-filter [ #10 * ] array-map


Retro:

needs array'
needs math'
with| array' math' |

create results 100 allot
new{ 1 1 2 3 5 8 13 21 }
[ dup odd? [ 100 * @results results + 1+ ! results ++ ] ifTrue ] apply
results display


-- crc

A. K.

unread,
Mar 2, 2013, 11:55:38 AM3/2/13
to
I am pretty sure Ruby or Haskell could do it even shorter

AND !!!

more readable. ;-)))

Marc Olschok

unread,
Mar 3, 2013, 5:11:16 PM3/3/13
to
Not much shorter I guess. E.g. in Haskell you could use

map (100*) $ filter odd [1,1,2,3,5,8,13,21]

which is quite close to the Factor example, or you could use

[ 100*x | x <- [1,1,2,3,5,8,13,21], odd x ]

which is perhaps the most readable to non-programmers.

And of course there is always Postscript:

[ [1 1 2 3 5 8 13 21] {dup 2 mod 0 eq {pop} {100 mul} ifelse} forall ]

But I do not see much difference in terms of readability, except that
Forth solutions may need to set up the data structures explicitly.
And I was surprised that Retroforth now has an array notation similar
to Postcript; I did not have time to follow its development in recent
years, it looks very interesting.

--
Marc

WJ

unread,
Dec 21, 2014, 4:50:56 AM12/21/14
to
Gauche Scheme:

gosh> (filter-map (^x (and (odd? x) (* 100 x))) (iota 22))
(100 300 500 700 900 1100 1300 1500 1700 1900 2100)


m...@iae.nl

unread,
Dec 21, 2014, 5:38:18 AM12/21/14
to
: oddseq ( "list" -- )
BEGIN 0. bl parse 2>r 2r@ >number nip 0=
WHILE drop 1 and IF 2r@ type ." 00 " ENDIF 2r> 2drop
REPEAT 2r> 2drop ;

\ oddseq 1 1 2 3 5 8 13 21 . 100 100 300 500 1300 2100 ok

In Forth this is actually LESS work than typing
"1 1 2 3 5 8 13 21" at the prompt (no dictionary
lookups).

-marcel

WJ

unread,
Dec 21, 2014, 6:15:45 AM12/21/14
to
Using recursion:

(let loop ((xs (iota 22)))
(if (null? xs)
'()
(if (odd? (car xs))
(cons (* 100 (car xs)) (loop (cdr xs)))
(loop (cdr xs)))))
0 new messages