]> gitweb.factorcode.org Git - factor.git/blob - basis/wrap/wrap.factor
wrap: 25% faster on benchmark.
[factor.git] / basis / wrap / wrap.factor
1 ! Copyright (C) 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays combinators combinators.short-circuit
4 fry kernel lists locals math sequences typed ;
5 IN: wrap
6
7 ! black is the text length, white is the whitespace length
8 TUPLE: element contents black white ;
9 C: <element> element
10
11 <PRIVATE
12
13 TYPED: element-length ( element: element -- n )
14     [ black>> ] [ white>> ] bi + ;
15
16 TUPLE: paragraph line-max line-ideal lines head-width tail-cost ;
17 C: <paragraph> paragraph
18
19 TYPED: top-fits? ( paragraph: paragraph -- ? )
20     [ head-width>> ]
21     [ dup lines>> 1list? [ line-ideal>> ] [ line-max>> ] if ] bi <= ;
22
23 TYPED: fits? ( paragraph: paragraph -- ? )
24     ! Make this not count spaces at end
25     { [ lines>> car 1list? ] [ top-fits? ] } 1|| ;
26
27 :: min-by ( seq quot -- elt )
28     f 1/0. seq [| key value newkey |
29         newkey quot call :> newvalue
30         newvalue value < [ newkey newvalue ] [ key value ] if
31     ] each drop ; inline
32
33 TYPED: paragraph-cost ( paragraph: paragraph -- cost )
34     dup lines>> 1list? [ drop 0 ] [
35         [ [ head-width>> ] [ line-ideal>> ] bi - sq ]
36         [ tail-cost>> ] bi +
37     ] if ;
38
39 : min-cost ( paragraphs -- paragraph )
40     [ paragraph-cost ] min-by ;
41
42 : new-line ( paragraph element -- paragraph )
43     {
44         [ drop [ line-max>> ] [ line-ideal>> ] bi ]
45         [ [ lines>> ] [ 1list ] bi* swons ]
46         [ nip black>> ]
47         [ drop paragraph-cost ]
48     } 2cleave <paragraph> ;
49
50 TYPED: add-element ( paragraph: paragraph element: element -- )
51     [ element-length [ + ] curry change-head-width ]
52     [ [ [ unswons ] dip swons swons ] curry change-lines ]
53     bi drop ;
54
55 : wrap-step ( paragraphs element -- paragraphs )
56     [ [ min-cost ] dip new-line ]
57     [ dupd '[ _ add-element ] each ]
58     2bi swap prefix
59     [ fits? ] filter ;
60
61 : 1paragraph ( line-max line-ideal element -- paragraph )
62     [ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
63
64 : post-process ( paragraph -- array )
65     lines>> [ [ contents>> ] lmap>array ] lmap>array ;
66
67 : initialize ( line-max line-ideal elements -- elements paragraph )
68     reverse unclip [ -rot ] dip 1paragraph 1array ;
69
70 PRIVATE>
71
72 : wrap ( elements line-max line-ideal -- array )
73     rot [ 2drop { } ] [
74         initialize
75         [ wrap-step ] reduce
76         min-cost
77         post-process
78     ] if-empty ;