source: project/chicken/branches/prerelease/manual/Unit extras @ 13240

Last change on this file since 13240 was 13240, checked in by felix winkelmann, 11 years ago

merged trunk svn rev. 13239 into prerelease

File size: 19.4 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
461=== Strings
462
463
464==== conc
465
466 [procedure] (conc X ...)
467
468Returns a string with the string-represenation of all arguments concatenated
469together. {{conc}} could be implemented as
470
471<enscript highlight=scheme>
472(define (conc . args)
473  (apply string-append (map ->string args)) )
474</enscript>
475
476
477
478==== ->string
479
480 [procedure] (->string X)
481
482Returns a string-representation of {{X}}.
483
484
485==== string-chop
486
487 [procedure] (string-chop STRING LENGTH)
488
489Returns a list of substrings taken by ''chopping'' {{STRING}} every {{LENGTH}}
490characters:
491
492<enscript highlight=scheme>
493(string-chop "one two three" 4)  ==>  ("one " "two " "thre" "e")
494</enscript>
495
496
497
498==== string-chomp
499
500 [procedure] (string-chomp STRING [SUFFIX])
501
502If {{STRING}} ends with {{SUFFIX}}, then this procedure returns a copy of its first argument with the suffix
503removed, otherwise returns {{STRING}} unchanged. {{SUFFIX}} defaults to {{"\n"}}.
504
505
506==== string-compare3
507
508 [procedure] (string-compare3 STRING1 STRING2)
509 [procedure] (string-compare3-ci STRING1 STRING2)
510
511Perform a three-way comparison between the {{STRING1}} and {{STRING2}},
512returning either {{-1}} if {{STRING1}} is lexicographically less
513than {{STRING2}}, {{0}} if it is equal, or {{1}} if it s greater.
514{{string-compare3-ci}} performs a case-insensitive comparison.
515
516
517==== string-intersperse
518
519 [procedure] (string-intersperse LIST [STRING])
520
521Returns a string that contains all strings in {{LIST}} concatenated
522together.  {{STRING}} is placed between each concatenated string and
523defaults to {{" "}}.
524
525<enscript highlight=scheme>
526(string-intersperse '("one" "two") "three")
527</enscript>
528
529is equivalent to
530
531<enscript highlight=scheme>
532(apply string-append (intersperse '("one" "two") "three"))
533</enscript>
534
535
536==== string-split
537
538 [procedure] (string-split STRING [DELIMITER-STRING [KEEPEMPTY]])
539
540Split string into substrings separated by the given delimiters. If
541no delimiters are specified, a string comprising the tab, newline and space characters
542is assumed. If the
543parameter {{KEEPEMPTY}} is given and not {{#f}}, then empty
544substrings are retained:
545
546<enscript highlight=scheme>
547(string-split "one  two  three") ==> ("one" "two" "three")
548(string-split "foo:bar::baz:" ":" #t) ==> ("foo" "bar" "" "baz" "")
549</enscript>
550
551
552==== string-translate
553
554 [procedure] (string-translate STRING FROM [TO])
555
556Returns a fresh copy of {{STRING}} with characters matching
557{{FROM}} translated to {{TO}}.  If {{TO}} is omitted, then
558matching characters are removed. {{FROM}} and {{TO}} may be
559a character, a string or a list. If both {{FROM}} and {{TO}}
560are strings, then the character at the same position in {{TO}}
561as the matching character in {{FROM}} is substituted.
562
563
564==== string-translate*
565
566 [procedure] (string-translate* STRING SMAP)
567
568Substitutes elements of {{STRING}} according to {{SMAP}}.
569{{SMAP}} should be an association-list where each element of the list
570is a pair of the form {{(MATCH \. REPLACEMENT)}}. Every occurrence of
571the string {{MATCH}} in {{STRING}} will be replaced by the string
572{{REPLACEMENT}}:
573
574<enscript highlight=scheme>
575(string-translate*
576  "<h1>this is a \"string\"</h1>"
577  '(("<" . "&lt;") (">" . "&gt;") ("\"" . "&quot;")) )
578=>  "&lt;h1&gt;this is a &quot;string&quot;&lt;/h1&gt;"
579</enscript>
580
581
582==== substring=?
583
584 [procedure] (substring=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
585 [procedure] (substring-ci=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
586
587Returns {{#t}} if the strings {{STRING1}} and {{STRING2}} are equal, or
588{{#f}} otherwise.
589The comparison starts at the positions {{START1}} and {{START2}} (which default
590to 0), comparing {{LENGTH}} characters (which defaults to the minimum of the remaining
591length of both strings).
592
593
594==== substring-index
595
596 [procedure] (substring-index WHICH WHERE [START])
597 [procedure] (substring-index-ci WHICH WHERE [START])
598
599Searches for first index in string {{WHERE}} where string
600{{WHICH}} occurs.  If the optional argument {{START}} is given,
601then the search starts at that index.  {{substring-index-ci}}
602is a case-insensitive version of {{substring-index}}.
603
604
605
606=== Combinators
607
608
609==== any?
610
611 [procedure] (any? X)
612
613Ignores its argument and always returns {{#t}}. This is actually useful sometimes.
614
615
616==== none?
617
618 [procedure] (none? X)
619
620Ignores its argument and always returns {{#f}}. This is actually useful sometimes.
621
622
623==== always?
624
625 [procedure] (always? ...)
626
627Ignores its arguments and always returns {{#t}}. This is actually useful sometimes.
628
629
630==== never?
631
632 [procedure] (never? ...)
633
634Ignores its arguments and always returns {{#f}}. This is actually useful sometimes.
635
636
637==== constantly
638
639 [procedure] (constantly X ...)
640
641Returns a procedure that always returns the values {{X ...}} regardless of the number and value of its arguments.
642
643<enscript highlight=scheme>
644(constantly X) <=> (lambda args X)
645</enscript>
646
647
648==== complement
649
650 [procedure] (complement PROC)
651
652Returns a procedure that returns the boolean inverse of {{PROC}}.
653
654<enscript highlight=scheme>
655(complement PROC) <=> (lambda (x) (not (PROC x)))
656</enscript>
657
658
659==== compose
660
661 [procedure] (compose PROC1 PROC2 ...)
662
663Returns a procedure that represents the composition of the
664argument-procedures {{PROC1 PROC2 ...}}.
665
666<enscript highlight=scheme>
667(compose F G) <=> (lambda args
668                      (call-with-values
669                         (lambda () (apply G args))
670                         F))
671</enscript>
672
673{{(compose)}} is equivalent to {{values}}.
674
675
676==== conjoin
677
678 [procedure] (conjoin PRED ...)
679
680Returns a procedure that returns {{#t}} if its argument satisfies the
681predicates {{PRED ...}}.
682<enscript highlight=scheme>
683((conjoin odd? positive?) 33)   ==>  #t
684((conjoin odd? positive?) -33)  ==>  #f
685</enscript>
686
687
688==== disjoin
689
690 [procedure] (disjoin PRED ...)
691
692Returns a procedure that returns {{#t}} if its argument satisfies any
693predicate {{PRED ...}}.
694<enscript highlight=scheme>
695((disjoin odd? positive?) 32)    ==>  #t
696((disjoin odd? positive?) -32)   ==>  #f
697</enscript>
698
699
700==== each
701
702 [procedure] (each PROC ...)
703
704Returns a procedure that applies {{PROC ...}} to its arguments, and returns the result(s)
705of the last procedure application. For example
706
707<enscript highlight=scheme>
708(each pp eval)
709</enscript>
710
711is equivalent to
712
713<enscript highlight=scheme>
714(lambda args
715  (apply pp args)
716  (apply eval args) )
717</enscript>
718
719{{(each PROC)}} is equivalent to {{PROC}} and {{(each)}} is equivalent to
720{{noop}}.
721
722
723==== flip
724
725 [procedure] (flip PROC)
726
727Returns a two-argument procedure that calls {{PROC}} with its
728arguments swapped:
729<enscript highlight=scheme>
730(flip PROC) <=> (lambda (x y) (PROC y x))
731</enscript>
732
733
734==== identity
735
736 [procedure] (identity X)
737
738Returns its sole argument {{X}}.
739
740
741==== project
742
743 [procedure] (project N)
744
745Returns a procedure that returns its {{N}}th argument (starting from 0).
746
747
748==== list-of
749
750 [procedure] (list-of PRED)
751
752Returns a procedure of one argument that returns {{#t}} when
753applied to a list of elements that all satisfy the predicate procedure
754{{PRED}}, or {{#f}} otherwise.
755
756<enscript highlight=scheme>
757((list-of even?) '(1 2 3))   ==> #f
758((list-of number?) '(1 2 3)) ==> #t
759</enscript>
760
761
762==== noop
763
764 [procedure] (noop X ...)
765
766Ignores it's arguments, does nothing and returns an unspecified value.
767
768
769==== o
770
771 [procedure] (o PROC ...)
772
773A single value version of {{compose}} (slightly faster). {{(o)}} is equivalent
774to {{identity}}.
775
776
777==== left-section
778
779 [procedure] (left-section PROC ARG0 ...)
780
781Returns an n-ary procedure that partially applies its' arguments {{ARG0 ...}}
782from the left (normal order). Sort of a n-ary curry.
783
784
785==== right-section
786
787 [procedure] (right-section PROC ARG0 ...)
788
789Returns an n-ary procedure that partially applies its' arguments {{ARG0 ...}}
790from the right (reverse order). Sort of a n-ary curry.
791
792
793=== Binary searching
794
795
796==== binary-search
797
798 [procedure] (binary-search SEQUENCE PROC)
799
800Performs a binary search in {{SEQUENCE}}, which should be a sorted
801list or vector.  {{PROC}} is called to compare items in the sequence,
802should accept a single argument and return an exact integer: zero if the
803searched value is equal to the current item, negative if the searched
804value is ''less'' than the current item, and positive otherwise.
805Returns the index of the found value or {{#f}} otherwise.
806
807Previous: [[Unit files]]
808
809Next: [[Unit srfi-1]]
Note: See TracBrowser for help on using the repository browser.