source: project/chicken/trunk/manual/Unit extras @ 13740

Last change on this file since 13740 was 13740, checked in by Kon Lovett, 11 years ago

Ordered by srfi #. Added srfi-69.

File size: 18.8 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>~%</td><td>
153write newline character
154</td></tr><tr><td> ~N</td><td>
155the same as {{~%}}
156</td></tr><tr><td> ~S</td><td>
157write the next argument
158</td></tr><tr><td> ~A</td><td>
159display the next argument
160</td></tr><tr><td> ~\n</td><td>
161skip all whitespace in the format-string until the next non-whitespace character
162</td></tr><tr><td> ~B</td><td>
163write the next argument as a binary number
164</td></tr><tr><td> ~O</td><td>
165write the next argument as an octal number
166</td></tr><tr><td> ~X</td><td>
167write the next argument as a hexadecimal number
168</td></tr><tr><td> ~C</td><td>
169write the next argument as a character
170</td></tr><tr><td> ~~</td><td>
171display `~'
172</td></tr><tr><td> ~!</td><td>
173flush all pending output
174</td></tr><tr><td> ~?</td><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=== Queues
195
196
197==== list->queue
198
199 [procedure] (list->queue LIST)
200
201Returns {{LIST}} converted into a queue, where the first element
202of the list is the same as the first element of the queue. The resulting
203queue may share memory with the list and the list should not be modified
204after this operation.
205
206
207==== make-queue
208
209 [procedure] (make-queue)
210
211Returns a newly created queue.
212
213
214==== queue?
215
216 [procedure] (queue? X)
217
218Returns {{#t}} if {{X}} is a queue, or {{#f}} otherwise.
219
220
221==== queue->list
222
223 [procedure] (queue->list QUEUE)
224
225Returns {{QUEUE}} converted into a list, where the first element
226of the list is the same as the first element of the queue. The resulting
227list may share memory with the queue object and should not be modified.
228
229
230==== queue-add!
231
232 [procedure] (queue-add! QUEUE X)
233
234Adds {{X}} to the rear of {{QUEUE}}.
235
236
237==== queue-empty?
238
239 [procedure] (queue-empty? QUEUE)
240
241Returns {{#t}} if {{QUEUE}} is empty, or {{#f}} otherwise.
242
243
244==== queue-first
245
246 [procedure] (queue-first QUEUE)
247
248Returns the first element of {{QUEUE}}. If {{QUEUE}} is empty
249an error is signaled
250
251
252==== queue-last
253
254 [procedure] (queue-last QUEUE)
255
256Returns the last element of {{QUEUE}}. If {{QUEUE}} is empty
257an error is signaled
258
259
260==== queue-remove!
261
262 [procedure] (queue-remove! QUEUE)
263
264Removes and returns the first element of {{QUEUE}}. If {{QUEUE}}
265is empty an error is signaled
266
267
268==== queue-push-back!
269
270 [procedure] (queue-push-back! QUEUE ITEM)
271
272Pushes an item into the first position of a queue, i.e. the next
273{{queue-remove!}} will return {{ITEM}}.
274
275
276==== queue-push-back-list!
277
278 [procedure] (queue-push-back-list! QUEUE LIST)
279
280Pushes the items in item-list back onto the queue,
281so that {{(car LIST)}} becomes the next removable item.
282
283
284
285=== Sorting
286
287
288==== merge
289
290 [procedure] (merge LIST1 LIST2 LESS?)
291 [procedure] (merge! LIST1 LIST2 LESS?)
292
293Joins two lists in sorted order. {{merge!}} is the destructive
294version of merge. {{LESS?  }} should be a procedure of two arguments,
295that returns true if the first argument is to be ordered before the
296second argument.
297
298
299==== sort
300
301 [procedure] (sort SEQUENCE LESS?)
302 [procedure] (sort! SEQUENCE LESS?)
303
304Sort {{SEQUENCE}}, which should be a list or a vector. {{sort!}}
305is the destructive version of sort.
306
307
308==== sorted?
309
310 [procedure] (sorted? SEQUENCE LESS?)
311
312Returns true if the list or vector {{SEQUENCE}} is already sorted.
313
314
315
316=== Random numbers
317
318
319==== random-seed
320
321 [procedure] (random-seed [SEED])
322
323Seeds the random number generator with {{SEED}} (an exact integer) or
324{{(current-seconds)}} if {{SEED}} is not given.
325
326
327==== random
328
329 [procedure] (random N)
330
331Returns an exact random integer from 0 to {{N}}-1.
332
333
334==== randomize
335
336 [procedure] (randomize [X])
337
338Set random-number seed. If {{X}} is not supplied, the current time is used.
339On startup (when the {{extras}} unit is initialized), the random number generator
340is initialized with the current time.
341
342
343=== Input/Output extensions
344
345==== pretty-print
346
347 [procedure] (pretty-print EXP [PORT])
348 [procedure] (pp EXP [PORT])
349
350Print expression nicely formatted. {{PORT}} defaults to the value
351of {{(current-output-port)}}.
352
353
354==== pretty-print-width
355(Parameter) Specifies the maximal line-width for pretty printing, after which line
356wrap will occur.
357
358==== read-byte
359==== write-byte
360
361 [procedure] (read-byte [PORT])
362 [procedure] (write-byte BYTE [PORT])
363
364Read/write a byte to the port given in {{PORT}}, which default to the values
365of {{(current-input-port)}} and {{(current-output-port)}}, respectively.
366
367==== read-file
368
369 [procedure] (read-file [FILE-OR-PORT [READER [MAXCOUNT]]])
370
371Returns a list containing all toplevel expressions
372read from the file or port {{FILE-OR-PORT}}. If no argument is given,
373input is read from the port that is the current value of {{(current-input-port)}}.
374After all expressions are read, and if the argument is a port, then the port will
375not be closed. The {{READER}} argument specifies the procedure used to read
376expressions from the given file or port and defaults to {{read}}. The reader
377procedure will be called with a single argument (an input port).
378If {{MAXCOUNT}} is given then only up to {{MAXCOUNT}} expressions will be read in.
379
380
381==== read-line
382==== write-line
383
384 [procedure] (read-line [PORT [LIMIT]])
385 [procedure] (write-line STRING [PORT])
386
387Line-input and -output. {{PORT}} defaults to the value of
388{{(current-input-port)}} and {{(current-output-port)}},
389respectively. If the optional argument {{LIMIT}} is given and
390not {{#f}}, then {{read-line}} reads at most {{LIMIT}}
391characters per line. {{read-line}} returns a string without the terminating newline and {{write-line}} adds a terminating newline  before outputting.
392
393
394==== read-lines
395
396 [procedure] (read-lines [PORT [MAX]])
397
398Read {{MAX}} or fewer lines from {{PORT}}. {{PORT}}
399defaults to the value of {{(current-input-port)}}. {{PORT}} may optionally be
400a string naming a file. Returns a list of strings, each string representing a line read, not including any line separation character(s).
401
402
403==== read-string
404==== read-string!
405==== write-string
406
407 [procedure] (read-string [NUM [PORT]])
408 [procedure] (read-string! NUM STRING [PORT [START]])
409 [procedure] (write-string STRING [NUM [PORT]]
410
411Read or write {{NUM}} characters from/to {{PORT}}, which defaults to the
412value of {{(current-input-port)}} or {{(current-output-port)}}, respectively.
413If {{NUM}} is {{#f}} or not given, then all data
414up to the end-of-file is read, or, in the case of {{write-string}} the whole
415string is written. If no more input is available, {{read-string}} returns the
416empty string. {{read-string!}} reads destructively into the given {{STRING}} argument,
417but never more characters that would fit into {{STRING}}. If {{START}} is given, then
418the read characters are stored starting at that position.
419{{read-string!}} returns the actual number of characters read.
420
421
422==== read-token
423
424 [procedure] (read-token PREDICATE [PORT])
425
426Reads characters from {{PORT}} (which defaults to the value of {{(current-input-port)}})
427and calls the procedure {{PREDICATE}} with each character until {{PREDICATE}} returns
428false. Returns a string with the accumulated characters.
429
430
431
432=== Strings
433
434
435==== conc
436
437 [procedure] (conc X ...)
438
439Returns a string with the string-represenation of all arguments concatenated
440together. {{conc}} could be implemented as
441
442<enscript highlight=scheme>
443(define (conc . args)
444  (apply string-append (map ->string args)) )
445</enscript>
446
447
448
449==== ->string
450
451 [procedure] (->string X)
452
453Returns a string-representation of {{X}}.
454
455
456==== string-chop
457
458 [procedure] (string-chop STRING LENGTH)
459
460Returns a list of substrings taken by ''chopping'' {{STRING}} every {{LENGTH}}
461characters:
462
463<enscript highlight=scheme>
464(string-chop "one two three" 4)  ==>  ("one " "two " "thre" "e")
465</enscript>
466
467
468
469==== string-chomp
470
471 [procedure] (string-chomp STRING [SUFFIX])
472
473If {{STRING}} ends with {{SUFFIX}}, then this procedure returns a copy of its first argument with the suffix
474removed, otherwise returns {{STRING}} unchanged. {{SUFFIX}} defaults to {{"\n"}}.
475
476
477==== string-compare3
478
479 [procedure] (string-compare3 STRING1 STRING2)
480 [procedure] (string-compare3-ci STRING1 STRING2)
481
482Perform a three-way comparison between the {{STRING1}} and {{STRING2}},
483returning either {{-1}} if {{STRING1}} is lexicographically less
484than {{STRING2}}, {{0}} if it is equal, or {{1}} if it s greater.
485{{string-compare3-ci}} performs a case-insensitive comparison.
486
487
488==== string-intersperse
489
490 [procedure] (string-intersperse LIST [STRING])
491
492Returns a string that contains all strings in {{LIST}} concatenated
493together.  {{STRING}} is placed between each concatenated string and
494defaults to {{" "}}.
495
496<enscript highlight=scheme>
497(string-intersperse '("one" "two") "three")
498</enscript>
499
500is equivalent to
501
502<enscript highlight=scheme>
503(apply string-append (intersperse '("one" "two") "three"))
504</enscript>
505
506
507==== string-split
508
509 [procedure] (string-split STRING [DELIMITER-STRING [KEEPEMPTY]])
510
511Split string into substrings separated by the given delimiters. If
512no delimiters are specified, a string comprising the tab, newline and space characters
513is assumed. If the
514parameter {{KEEPEMPTY}} is given and not {{#f}}, then empty
515substrings are retained:
516
517<enscript highlight=scheme>
518(string-split "one  two  three") ==> ("one" "two" "three")
519(string-split "foo:bar::baz:" ":" #t) ==> ("foo" "bar" "" "baz" "")
520</enscript>
521
522
523==== string-translate
524
525 [procedure] (string-translate STRING FROM [TO])
526
527Returns a fresh copy of {{STRING}} with characters matching
528{{FROM}} translated to {{TO}}.  If {{TO}} is omitted, then
529matching characters are removed. {{FROM}} and {{TO}} may be
530a character, a string or a list. If both {{FROM}} and {{TO}}
531are strings, then the character at the same position in {{TO}}
532as the matching character in {{FROM}} is substituted.
533
534
535==== string-translate*
536
537 [procedure] (string-translate* STRING SMAP)
538
539Substitutes elements of {{STRING}} according to {{SMAP}}.
540{{SMAP}} should be an association-list where each element of the list
541is a pair of the form {{(MATCH \. REPLACEMENT)}}. Every occurrence of
542the string {{MATCH}} in {{STRING}} will be replaced by the string
543{{REPLACEMENT}}:
544
545<enscript highlight=scheme>
546(string-translate*
547  "<h1>this is a \"string\"</h1>"
548  '(("<" . "&lt;") (">" . "&gt;") ("\"" . "&quot;")) )
549=>  "&lt;h1&gt;this is a &quot;string&quot;&lt;/h1&gt;"
550</enscript>
551
552
553==== substring=?
554
555 [procedure] (substring=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
556 [procedure] (substring-ci=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
557
558Returns {{#t}} if the strings {{STRING1}} and {{STRING2}} are equal, or
559{{#f}} otherwise.
560The comparison starts at the positions {{START1}} and {{START2}} (which default
561to 0), comparing {{LENGTH}} characters (which defaults to the minimum of the remaining
562length of both strings).
563
564
565==== substring-index
566
567 [procedure] (substring-index WHICH WHERE [START])
568 [procedure] (substring-index-ci WHICH WHERE [START])
569
570Searches for first index in string {{WHERE}} where string
571{{WHICH}} occurs.  If the optional argument {{START}} is given,
572then the search starts at that index.  {{substring-index-ci}}
573is a case-insensitive version of {{substring-index}}.
574
575
576
577=== Combinators
578
579
580==== any?
581
582 [procedure] (any? X)
583
584Ignores its argument and always returns {{#t}}. This is actually useful sometimes.
585
586
587==== none?
588
589 [procedure] (none? X)
590
591Ignores its argument and always returns {{#f}}. This is actually useful sometimes.
592
593
594==== always?
595
596 [procedure] (always? ...)
597
598Ignores its arguments and always returns {{#t}}. This is actually useful sometimes.
599
600
601==== never?
602
603 [procedure] (never? ...)
604
605Ignores its arguments and always returns {{#f}}. This is actually useful sometimes.
606
607
608==== constantly
609
610 [procedure] (constantly X ...)
611
612Returns a procedure that always returns the values {{X ...}} regardless of the number and value of its arguments.
613
614<enscript highlight=scheme>
615(constantly X) <=> (lambda args X)
616</enscript>
617
618
619==== complement
620
621 [procedure] (complement PROC)
622
623Returns a procedure that returns the boolean inverse of {{PROC}}.
624
625<enscript highlight=scheme>
626(complement PROC) <=> (lambda (x) (not (PROC x)))
627</enscript>
628
629
630==== compose
631
632 [procedure] (compose PROC1 PROC2 ...)
633
634Returns a procedure that represents the composition of the
635argument-procedures {{PROC1 PROC2 ...}}.
636
637<enscript highlight=scheme>
638(compose F G) <=> (lambda args
639                      (call-with-values
640                         (lambda () (apply G args))
641                         F))
642</enscript>
643
644{{(compose)}} is equivalent to {{values}}.
645
646
647==== conjoin
648
649 [procedure] (conjoin PRED ...)
650
651Returns a procedure that returns {{#t}} if its argument satisfies the
652predicates {{PRED ...}}.
653<enscript highlight=scheme>
654((conjoin odd? positive?) 33)   ==>  #t
655((conjoin odd? positive?) -33)  ==>  #f
656</enscript>
657
658
659==== disjoin
660
661 [procedure] (disjoin PRED ...)
662
663Returns a procedure that returns {{#t}} if its argument satisfies any
664predicate {{PRED ...}}.
665<enscript highlight=scheme>
666((disjoin odd? positive?) 32)    ==>  #t
667((disjoin odd? positive?) -32)   ==>  #f
668</enscript>
669
670
671==== each
672
673 [procedure] (each PROC ...)
674
675Returns a procedure that applies {{PROC ...}} to its arguments, and returns the result(s)
676of the last procedure application. For example
677
678<enscript highlight=scheme>
679(each pp eval)
680</enscript>
681
682is equivalent to
683
684<enscript highlight=scheme>
685(lambda args
686  (apply pp args)
687  (apply eval args) )
688</enscript>
689
690{{(each PROC)}} is equivalent to {{PROC}} and {{(each)}} is equivalent to
691{{noop}}.
692
693
694==== flip
695
696 [procedure] (flip PROC)
697
698Returns a two-argument procedure that calls {{PROC}} with its
699arguments swapped:
700<enscript highlight=scheme>
701(flip PROC) <=> (lambda (x y) (PROC y x))
702</enscript>
703
704
705==== identity
706
707 [procedure] (identity X)
708
709Returns its sole argument {{X}}.
710
711
712==== project
713
714 [procedure] (project N)
715
716Returns a procedure that returns its {{N}}th argument (starting from 0).
717
718
719==== list-of
720
721 [procedure] (list-of PRED)
722
723Returns a procedure of one argument that returns {{#t}} when
724applied to a list of elements that all satisfy the predicate procedure
725{{PRED}}, or {{#f}} otherwise.
726
727<enscript highlight=scheme>
728((list-of even?) '(1 2 3))   ==> #f
729((list-of number?) '(1 2 3)) ==> #t
730</enscript>
731
732
733==== noop
734
735 [procedure] (noop X ...)
736
737Ignores it's arguments, does nothing and returns an unspecified value.
738
739
740==== o
741
742 [procedure] (o PROC ...)
743
744A single value version of {{compose}} (slightly faster). {{(o)}} is equivalent
745to {{identity}}.
746
747
748==== left-section
749
750 [procedure] (left-section PROC ARG0 ...)
751
752Returns an n-ary procedure that partially applies its' arguments {{ARG0 ...}}
753from the left (normal order). Sort of a n-ary curry.
754
755
756==== right-section
757
758 [procedure] (right-section PROC ARG0 ...)
759
760Returns an n-ary procedure that partially applies its' arguments {{ARG0 ...}}
761from the right (reverse order). Sort of a n-ary curry.
762
763
764=== Binary searching
765
766
767==== binary-search
768
769 [procedure] (binary-search SEQUENCE PROC)
770
771Performs a binary search in {{SEQUENCE}}, which should be a sorted
772list or vector.  {{PROC}} is called to compare items in the sequence,
773should accept a single argument and return an exact integer: zero if the
774searched value is equal to the current item, negative if the searched
775value is ''less'' than the current item, and positive otherwise.
776Returns the index of the found value or {{#f}} otherwise.
777
778---
779Previous: [[Unit files]]
780
781Next: [[Unit regex]]
Note: See TracBrowser for help on using the repository browser.