source: project/chicken/branches/hygienic/manual/Unit extras @ 10952

Last change on this file since 10952 was 10952, checked in by felix winkelmann, 13 years ago

merged changed from trunk rev. 10622:10950 (untested)

File size: 19.9 KB
Line 
1[[tags: manual]]
2[[toc:]]
3
4== Unit extras
5
6This unit contains a collection of useful utility definitions.
7This unit is used by default, unless the program
8is compiled with the {{-explicit-use}} option.
9
10
11=== Lists
12
13
14==== alist-ref
15
16 [procedure] (alist-ref KEY ALIST [TEST [DEFAULT]])
17
18Looks up {{KEY}} in {{ALIST}} using {{TEST}} as the comparison function (or {{eqv?}} if
19no test was given) and returns the cdr of the found pair, or {{DEFAULT}} (which defaults to {{#f}}).
20
21
22==== alist-update!
23
24 [procedure] (alist-update! KEY VALUE ALIST [TEST])
25
26If the list {{ALIST}} contains a pair of the form {{(KEY . X)}}, then this procedure
27replaces {{X}} with {{VALUE}} and returns {{ALIST}}. If {{ALIST}} contains no such item, then
28{{alist-update!}} returns {{((KEY . VALUE) . ALIST)}}. The optional argument
29{{TEST}} specifies the comparison procedure to search a matching pair in {{ALIST}}
30and defaults to {{eqv?}}.
31
32
33==== atom?
34
35 [procedure] (atom? X)
36
37Returns {{#t}} if {{X}} is not a pair. This is identical to {{not-pair?}} from [[Unit srfi-1]] but
38kept for historical reasons.
39
40
41==== rassoc
42
43 [procedure] (rassoc KEY LIST [TEST])
44
45Similar to {{assoc}}, but compares {{KEY}} with the {{cdr}} of each pair in {{LIST}} using
46{{TEST}} as the comparison procedures (which defaults to {{eqv?}}.
47
48
49==== butlast
50
51 [procedure] (butlast LIST)
52
53Returns a fresh list with all elements but the last of {{LIST}}.
54
55
56==== chop
57
58 [procedure] (chop LIST N)
59
60Returns a new list of sublists, where each sublist contains {{N}}
61elements of {{LIST}}. If {{LIST}} has a length that is not
62a multiple of {{N}}, then the last sublist contains the remaining
63elements.
64
65<enscript highlight=scheme>
66(chop '(1 2 3 4 5 6) 2) ==> ((1 2) (3 4) (5 6))
67(chop '(a b c d) 3)     ==> ((a b c) (d))
68</enscript>
69
70
71
72==== compress
73
74 [procedure] (compress BLIST LIST)
75
76Returns a new list with elements taken from {{LIST}} with
77corresponding true values in the list {{BLIST}}.
78
79<enscript highlight=scheme>
80(define nums '(99 100 110 401 1234))
81(compress (map odd? nums) nums)      ==> (99 401)
82</enscript>
83
84
85==== flatten
86
87 [procedure] (flatten LIST1 ...)
88
89Returns {{LIST1 ...}} concatenated together, with nested lists
90removed (flattened).
91
92
93==== intersperse
94
95 [procedure] (intersperse LIST X)
96
97Returns a new list with {{X}} placed between each element.
98
99
100==== join
101
102 [procedure] (join LISTOFLISTS [LIST])
103
104Concatenates the lists in {{LISTOFLISTS}} with {{LIST}} placed
105between each sublist. {{LIST}} defaults to the empty list.
106
107<enscript highlight=scheme>
108(join '((a b) (c d) (e)) '(x y)) ==> (a b x y c d x y e)
109(join '((p q) () (r (s) t)) '(-))  ==> (p q - - r (s) t)
110</enscript>
111
112{{join}} could be implemented as follows:
113
114<enscript highlight=scheme>
115(define (join lstoflsts #!optional (lst '()))
116  (apply append (intersperse lstoflists lst)) )
117</enscript>
118
119
120==== shuffle
121
122 [procedure] (shuffle LIST)
123
124Returns {{LIST}} with its elements sorted in a random order.
125
126
127==== tail?
128
129 [procedure] (tail? X LIST)
130
131Returns true if {{X}} is one of the tails (cdr's) of {{LIST}}.
132
133
134
135=== Formatted output
136
137
138==== printf
139==== fprintf
140==== sprintf
141
142 [procedure] (fprintf PORT FORMATSTRING ARG ...)
143 [procedure] (printf FORMATSTRING ARG ...)
144 [procedure] (sprintf FORMATSTRING ARG ...)
145
146Simple formatted output to a given port ({{fprintf}}), the
147value of {{(current-output-port)}} ({{printf}}), or a string
148({{sprintf}}).  The {{FORMATSTRING}} can contain any sequence
149of characters.  There must be at least as many {{ARG}} arguments given as there are format directives that require an argument in {{FORMATSTRING}}.  Extra {{ARG}} arguments are ignored.  The character `~' prefixes special formatting directives:
150
151<table>
152<tr><td> ~%
153write newline character
154</td></tr><tr><td> ~N
155the same as {{~%}}
156</td></tr><tr><td> ~S
157write the next argument
158</td></tr><tr><td> ~A
159display the next argument
160</td></tr><tr><td> ~\n
161skip all whitespace in the format-string until the next non-whitespace character
162</td></tr><tr><td> ~B
163write the next argument as a binary number
164</td></tr><tr><td> ~O
165write the next argument as an octal number
166</td></tr><tr><td> ~X
167write the next argument as a hexadecimal number
168</td></tr><tr><td> ~C
169write the next argument as a character
170</td></tr><tr><td> ~~
171display `~'
172</td></tr><tr><td> ~!
173flush all pending output
174</td></tr><tr><td> ~?
175invoke formatted output routine recursively with the next two arguments as format-string and list of parameters
176</td></tr></table>
177
178
179==== format
180
181 [procedure] (format [DESTINATION] FORMATSTRING ARG ...)
182
183The parameters  {{FORMATSTRING}} and {{ARG ...}} are as for
184({{printf}}/{{sprintf}}/{{fprintf}}).
185
186The optional {{DESTINATION}}, when supplied, performs
187a ({{sprintf}}) for a  {{#f}},
188a ({{printf}}) for a {{#t}},
189and a ({{fprintf}}) for an output-port.
190When missing a ({{sprintf}}) is performed.
191
192
193
194=== Hash tables
195
196CHICKEN implements SRFI-69. For more information,
197see [[http://srfi.schemers.org/srfi-69/srfi-69.html|SRFI-69]].
198
199A setter for {{hash-table-ref}} is defined, so
200
201<enscript highlight=scheme>
202(set! (hash-table-ref HT KEY) VAL)
203</enscript>
204
205is equivalent to
206
207<enscript highlight=scheme>
208(hash-table-set! HT KEY VAL)
209</enscript>
210
211As an extension to SRFI-69, {{hash-table-update!}} and {{hash-table-update!/default}} return
212the new value (after applying the update procedure).
213
214==== hash-table-remove!
215
216 [procedure] (hash-table-remove! HASHTABLE PROC)
217
218Calls {{PROC}} for all entries in {{HASHTABLE}} with the key and value of each
219entry. If {{PROC}} returns true, then that entry is removed.
220
221
222
223=== Queues
224
225
226==== list->queue
227
228 [procedure] (list->queue LIST)
229
230Returns {{LIST}} converted into a queue, where the first element
231of the list is the same as the first element of the queue. The resulting
232queue may share memory with the list and the list should not be modified
233after this operation.
234
235
236==== make-queue
237
238 [procedure] (make-queue)
239
240Returns a newly created queue.
241
242
243==== queue?
244
245 [procedure] (queue? X)
246
247Returns {{#t}} if {{X}} is a queue, or {{#f}} otherwise.
248
249
250==== queue->list
251
252 [procedure] (queue->list QUEUE)
253
254Returns {{QUEUE}} converted into a list, where the first element
255of the list is the same as the first element of the queue. The resulting
256list may share memory with the queue object and should not be modified.
257
258
259==== queue-add!
260
261 [procedure] (queue-add! QUEUE X)
262
263Adds {{X}} to the rear of {{QUEUE}}.
264
265
266==== queue-empty?
267
268 [procedure] (queue-empty? QUEUE)
269
270Returns {{#t}} if {{QUEUE}} is empty, or {{#f}} otherwise.
271
272
273==== queue-first
274
275 [procedure] (queue-first QUEUE)
276
277Returns the first element of {{QUEUE}}. If {{QUEUE}} is empty
278an error is signaled
279
280
281==== queue-last
282
283 [procedure] (queue-last QUEUE)
284
285Returns the last element of {{QUEUE}}. If {{QUEUE}} is empty
286an error is signaled
287
288
289==== queue-remove!
290
291 [procedure] (queue-remove! QUEUE)
292
293Removes and returns the first element of {{QUEUE}}. If {{QUEUE}}
294is empty an error is signaled
295
296
297==== queue-push-back!
298
299 [procedure] (queue-push-back! QUEUE ITEM)
300
301Pushes an item into the first position of a queue, i.e. the next
302{{queue-remove!}} will return {{ITEM}}.
303
304
305==== queue-push-back-list!
306
307 [procedure] (queue-push-back-list! QUEUE LIST)
308
309Pushes the items in item-list back onto the queue,
310so that {{(car LIST)}} becomes the next removable item.
311
312
313
314=== Sorting
315
316
317==== merge
318
319 [procedure] (merge LIST1 LIST2 LESS?)
320 [procedure] (merge! LIST1 LIST2 LESS?)
321
322Joins two lists in sorted order. {{merge!}} is the destructive
323version of merge. {{LESS?  }} should be a procedure of two arguments,
324that returns true if the first argument is to be ordered before the
325second argument.
326
327
328==== sort
329
330 [procedure] (sort SEQUENCE LESS?)
331 [procedure] (sort! SEQUENCE LESS?)
332
333Sort {{SEQUENCE}}, which should be a list or a vector. {{sort!}}
334is the destructive version of sort.
335
336
337==== sorted?
338
339 [procedure] (sorted? SEQUENCE LESS?)
340
341Returns true if the list or vector {{SEQUENCE}} is already sorted.
342
343
344
345=== Random numbers
346
347
348==== random-seed
349
350 [procedure] (random-seed [SEED])
351
352Seeds the random number generator with {{SEED}} (an exact integer) or
353{{(current-seconds)}} if {{SEED}} is not given.
354
355
356==== random
357
358 [procedure] (random N)
359
360Returns an exact random integer from 0 to {{N}}-1.
361
362
363==== randomize
364
365 [procedure] (randomize [X])
366
367Set random-number seed. If {{X}} is not supplied, the current time is used.
368On startup (when the {{extras}} unit is initialized), the random number generator
369is initialized with the current time.
370
371
372=== Input/Output extensions
373
374==== pretty-print
375
376 [procedure] (pretty-print EXP [PORT])
377 [procedure] (pp EXP [PORT])
378
379Print expression nicely formatted. {{PORT}} defaults to the value
380of {{(current-output-port)}}.
381
382
383==== pretty-print-width
384(Parameter) Specifies the maximal line-width for pretty printing, after which line
385wrap will occur.
386
387==== read-byte
388==== write-byte
389
390 [procedure] (read-byte [PORT])
391 [procedure] (write-byte BYTE [PORT])
392
393Read/write a byte to the port given in {{PORT}}, which default to the values
394of {{(current-input-port)}} and {{(current-output-port)}}, respectively.
395
396==== read-file
397
398 [procedure] (read-file [FILE-OR-PORT [READER [MAXCOUNT]]])
399
400Returns a list containing all toplevel expressions
401read from the file or port {{FILE-OR-PORT}}. If no argument is given,
402input is read from the port that is the current value of {{(current-input-port)}}.
403After all expressions are read, and if the argument is a port, then the port will
404not be closed. The {{READER}} argument specifies the procedure used to read
405expressions from the given file or port and defaults to {{read}}. The reader
406procedure will be called with a single argument (an input port).
407If {{MAXCOUNT}} is given then only up to {{MAXCOUNT}} expressions will be read in.
408
409
410==== read-line
411==== write-line
412
413 [procedure] (read-line [PORT [LIMIT]])
414 [procedure] (write-line STRING [PORT])
415
416Line-input and -output. {{PORT}} defaults to the value of
417{{(current-input-port)}} and {{(current-output-port)}},
418respectively. If the optional argument {{LIMIT}} is given and
419not {{#f}}, then {{read-line}} reads at most {{LIMIT}}
420characters per line. {{read-line}} returns a string without the terminating newline and {{write-line}} adds a terminating newline  before outputting.
421
422
423==== read-lines
424
425 [procedure] (read-lines [PORT [MAX]])
426
427Read {{MAX}} or fewer lines from {{PORT}}. {{PORT}}
428defaults to the value of {{(current-input-port)}}. {{PORT}} may optionally be
429a string naming a file. Returns a list of strings, each string representing a line read, not including any line separation character(s).
430
431
432==== read-string
433==== read-string!
434==== write-string
435
436 [procedure] (read-string [NUM [PORT]])
437 [procedure] (read-string! NUM STRING [PORT [START]])
438 [procedure] (write-string STRING [NUM [PORT]]
439
440Read or write {{NUM}} characters from/to {{PORT}}, which defaults to the
441value of {{(current-input-port)}} or {{(current-output-port)}}, respectively.
442If {{NUM}} is {{#f}} or not given, then all data
443up to the end-of-file is read, or, in the case of {{write-string}} the whole
444string is written. If no more input is available, {{read-string}} returns the
445empty string. {{read-string!}} reads destructively into the given {{STRING}} argument,
446but never more characters that would fit into {{STRING}}. If {{START}} is given, then
447the read characters are stored starting at that position.
448{{read-string!}} returns the actual number of characters read.
449
450
451==== read-token
452
453 [procedure] (read-token PREDICATE [PORT])
454
455Reads characters from {{PORT}} (which defaults to the value of {{(current-input-port)}})
456and calls the procedure {{PREDICATE}} with each character until {{PREDICATE}} returns
457false. Returns a string with the accumulated characters.
458
459
460==== with-error-output-to-port
461
462 [procedure] (with-error-output-to-port PORT THUNK)
463
464Call procedure {{THUNK}} with the current error output-port
465temporarily bound to {{PORT}}.
466
467
468==== with-input-from-port
469
470 [procedure] (with-input-from-port PORT THUNK)
471
472Call procedure {{THUNK}} with the current input-port temporarily
473bound to {{PORT}}.
474
475
476==== with-output-to-port
477
478 [procedure] (with-output-to-port PORT THUNK)
479
480Call procedure {{THUNK}} with the current output-port temporarily
481bound to {{PORT}}.
482
483
484
485=== Strings
486
487
488==== conc
489
490 [procedure] (conc X ...)
491
492Returns a string with the string-represenation of all arguments concatenated
493together. {{conc}} could be implemented as
494
495<enscript highlight=scheme>
496(define (conc . args)
497  (apply string-append (map ->string args)) )
498</enscript>
499
500
501
502==== ->string
503
504 [procedure] (->string X)
505
506Returns a string-representation of {{X}}.
507
508
509==== string-chop
510
511 [procedure] (string-chop STRING LENGTH)
512
513Returns a list of substrings taken by ''chopping'' {{STRING}} every {{LENGTH}}
514characters:
515
516<enscript highlight=scheme>
517(string-chop "one two three" 4)  ==>  ("one " "two " "thre" "e")
518</enscript>
519
520
521
522==== string-chomp
523
524 [procedure] (string-chomp STRING [SUFFIX])
525
526If {{STRING}} ends with {{SUFFIX}}, then this procedure returns a copy of its first argument with the suffix
527removed, otherwise returns {{STRING}} unchanged. {{SUFFIX}} defaults to {{"\n"}}.
528
529
530==== string-compare3
531
532 [procedure] (string-compare3 STRING1 STRING2)
533 [procedure] (string-compare3-ci STRING1 STRING2)
534
535Perform a three-way comparison between the {{STRING1}} and {{STRING2}},
536returning either {{-1}} if {{STRING1}} is lexicographically less
537than {{STRING2}}, {{0}} if it is equal, or {{1}} if it s greater.
538{{string-compare3-ci}} performs a case-insensitive comparison.
539
540
541==== string-intersperse
542
543 [procedure] (string-intersperse LIST [STRING])
544
545Returns a string that contains all strings in {{LIST}} concatenated
546together.  {{STRING}} is placed between each concatenated string and
547defaults to {{" "}}.
548
549<enscript highlight=scheme>
550(string-intersperse '("one" "two") "three")
551</enscript>
552
553is equivalent to
554
555<enscript highlight=scheme>
556(apply string-append (intersperse '("one" "two") "three"))
557</enscript>
558
559
560==== string-split
561
562 [procedure] (string-split STRING [DELIMITER-STRING [KEEPEMPTY]])
563
564Split string into substrings separated by the given delimiters. If
565no delimiters are specified, a string comprising the tab, newline and space characters
566is assumed. If the
567parameter {{KEEPEMPTY}} is given and not {{#f}}, then empty
568substrings are retained:
569
570<enscript highlight=scheme>
571(string-split "one  two  three") ==> ("one" "two" "three")
572(string-split "foo:bar::baz:" ":" #t) ==> ("foo" "bar" "" "baz" "")
573</enscript>
574
575
576==== string-translate
577
578 [procedure] (string-translate STRING FROM [TO])
579
580Returns a fresh copy of {{STRING}} with characters matching
581{{FROM}} translated to {{TO}}.  If {{TO}} is omitted, then
582matching characters are removed. {{FROM}} and {{TO}} may be
583a character, a string or a list. If both {{FROM}} and {{TO}}
584are strings, then the character at the same position in {{TO}}
585as the matching character in {{FROM}} is substituted.
586
587
588==== string-translate*
589
590 [procedure] (string-translate* STRING SMAP)
591
592Substitutes elements of {{STRING}} according to {{SMAP}}.
593{{SMAP}} should be an association-list where each element of the list
594is a pair of the form {{(MATCH \. REPLACEMENT)}}. Every occurrence of
595the string {{MATCH}} in {{STRING}} will be replaced by the string
596{{REPLACEMENT}}:
597
598<enscript highlight=scheme>
599(string-translate*
600  "<h1>this is a \"string\"</h1>"
601  '(("<" . "&lt;") (">" . "&gt;") ("\"" . "&quot;")) )
602=>  "&lt;h1&gt;this is a &quot;string&quot;&lt;/h1&gt;"
603</enscript>
604
605
606==== substring=?
607
608 [procedure] (substring=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
609 [procedure] (substring-ci=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
610
611Returns {{#t}} if the strings {{STRING1}} and {{STRING2}} are equal, or
612{{#f}} otherwise.
613The comparison starts at the positions {{START1}} and {{START2}} (which default
614to 0), comparing {{LENGTH}} characters (which defaults to the minimum of the remaining
615length of both strings).
616
617
618==== substring-index
619
620 [procedure] (substring-index WHICH WHERE [START])
621 [procedure] (substring-index-ci WHICH WHERE [START])
622
623Searches for first index in string {{WHERE}} where string
624{{WHICH}} occurs.  If the optional argument {{START}} is given,
625then the search starts at that index.  {{substring-index-ci}}
626is a case-insensitive version of {{substring-index}}.
627
628
629
630=== Combinators
631
632
633==== any?
634
635 [procedure] (any? X)
636
637Ignores its argument and always returns {{#t}}. This is actually useful sometimes.
638
639
640==== none?
641
642 [procedure] (none? X)
643
644Ignores its argument and always returns {{#f}}. This is actually useful sometimes.
645
646
647==== always?
648
649 [procedure] (always? ...)
650
651Ignores its arguments and always returns {{#t}}. This is actually useful sometimes.
652
653
654==== never?
655
656 [procedure] (never? ...)
657
658Ignores its arguments and always returns {{#f}}. This is actually useful sometimes.
659
660
661==== constantly
662
663 [procedure] (constantly X ...)
664
665Returns a procedure that always returns the values {{X ...}} regardless of the number and value of its arguments.
666
667<enscript highlight=scheme>
668(constantly X) <=> (lambda args X)
669</enscript>
670
671
672==== complement
673
674 [procedure] (complement PROC)
675
676Returns a procedure that returns the boolean inverse of {{PROC}}.
677
678<enscript highlight=scheme>
679(complement PROC) <=> (lambda (x) (not (PROC x)))
680</enscript>
681
682
683==== compose
684
685 [procedure] (compose PROC1 PROC2 ...)
686
687Returns a procedure that represents the composition of the
688argument-procedures {{PROC1 PROC2 ...}}.
689
690<enscript highlight=scheme>
691(compose F G) <=> (lambda args
692                      (call-with-values
693                         (lambda () (apply G args))
694                         F))
695</enscript>
696
697{{(compose)}} is equivalent to {{values}}.
698
699
700==== conjoin
701
702 [procedure] (conjoin PRED ...)
703
704Returns a procedure that returns {{#t}} if its argument satisfies the
705predicates {{PRED ...}}.
706<enscript highlight=scheme>
707((conjoin odd? positive?) 33)   ==>  #t
708((conjoin odd? positive?) -33)  ==>  #f
709</enscript>
710
711
712==== disjoin
713
714 [procedure] (disjoin PRED ...)
715
716Returns a procedure that returns {{#t}} if its argument satisfies any
717predicate {{PRED ...}}.
718<enscript highlight=scheme>
719((disjoin odd? positive?) 32)    ==>  #t
720((disjoin odd? positive?) -32)   ==>  #f
721</enscript>
722
723
724==== each
725
726 [procedure] (each PROC ...)
727
728Returns a procedure that applies {{PROC ...}} to its arguments, and returns the result(s)
729of the last procedure application. For example
730
731<enscript highlight=scheme>
732(each pp eval)
733</enscript>
734
735is equivalent to
736
737<enscript highlight=scheme>
738(lambda args
739  (apply pp args)
740  (apply eval args) )
741</enscript>
742
743{{(each PROC)}} is equivalent to {{PROC}} and {{(each)}} is equivalent to
744{{noop}}.
745
746
747==== flip
748
749 [procedure] (flip PROC)
750
751Returns a two-argument procedure that calls {{PROC}} with its
752arguments swapped:
753<enscript highlight=scheme>
754(flip PROC) <=> (lambda (x y) (PROC y x))
755</enscript>
756
757
758==== identity
759
760 [procedure] (identity X)
761
762Returns its sole argument {{X}}.
763
764
765==== project
766
767 [procedure] (project N)
768
769Returns a procedure that returns its {{N}}th argument (starting from 0).
770
771
772==== list-of
773
774 [procedure] (list-of PRED)
775
776Returns a procedure of one argument that returns {{#t}} when
777applied to a list of elements that all satisfy the predicate procedure
778{{PRED}}, or {{#f}} otherwise.
779
780<enscript highlight=scheme>
781((list-of even?) '(1 2 3))   ==> #f
782((list-of number?) '(1 2 3)) ==> #t
783</enscript>
784
785
786==== noop
787
788 [procedure] (noop X ...)
789
790Ignores it's arguments, does nothing and returns an unspecified value.
791
792
793==== o
794
795 [procedure] (o PROC ...)
796
797A single value version of {{compose}} (slightly faster). {{(o)}} is equivalent
798to {{identity}}.
799
800
801==== left-section
802
803 [procedure] (left-section PROC ARG0 ...)
804
805Returns an n-ary procedure that partially applies its' arguments {{ARG0 ...}}
806from the left (normal order). Sort of a n-ary curry.
807
808
809==== right-section
810
811 [procedure] (right-section PROC ARG0 ...)
812
813Returns an n-ary procedure that partially applies its' arguments {{ARG0 ...}}
814from the right (reverse order). Sort of a n-ary curry.
815
816
817=== Binary searching
818
819
820==== binary-search
821
822 [procedure] (binary-search SEQUENCE PROC)
823
824Performs a binary search in {{SEQUENCE}}, which should be a sorted
825list or vector.  {{PROC}} is called to compare items in the sequence,
826should accept a single argument and return an exact integer: zero if the
827searched value is equal to the current item, negative if the searched
828value is ''less'' than the current item, and positive otherwise.
829Returns the index of the found value or {{#f}} otherwise.
830
831Previous: [[Unit eval]]
832
833Next: [[Unit srfi-1]]
Note: See TracBrowser for help on using the repository browser.