]> gitweb.factorcode.org Git - factor.git/commitdiff
io.random: cleanup using "each-numbered-line", implement "random-lines".
authorJohn Benediktsson <mrjbq7@gmail.com>
Tue, 23 Oct 2012 23:11:07 +0000 (16:11 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Tue, 23 Oct 2012 23:11:07 +0000 (16:11 -0700)
extra/io/random/random.factor

index 3186e263e4f7ac98791dcd7e01e8c150614fa57b..d9ce6c6838a66071957ca7b68867d52c787f2056 100644 (file)
@@ -1,16 +1,28 @@
 ! Copyright (C) 2012 John Benediktsson
 ! See http://factorcode.org/license.txt for BSD license
 
-USING: io kernel math random ;
+USING: fry io kernel locals math random sequences
+sequences.extras ;
 
 IN: io.random
 
 <PRIVATE
 
-: ?replace ( old new n -- old/new )
-    random zero? [ nip ] [ drop ] if ;
+: each-numbered-line ( ... quot: ( ... line number -- ... ) -- ... )
+    [ 1 ] dip '[ swap [ @ ] [ 1 + ] bi ] each-line drop ; inline
 
 PRIVATE>
 
-: random-readln ( -- line/f )
-    f 1 [ swap [ ?replace ] [ 1 + ] bi ] each-line drop ;
+: random-line ( -- line/f )
+    f [ random zero? [ nip ] [ drop ] if ] each-numbered-line ;
+
+:: random-lines ( n -- lines )
+    V{ } clone :> accum
+    [| line line# |
+        line# random :> r
+        r n < [
+            line# n <
+            [ line r accum insert-nth! ]
+            [ line r accum set-nth ] if
+        ] when
+    ] each-numbered-line accum ;