source: project/wiki/Unit extras @ 2752

Last change on this file since 2752 was 2752, checked in by felix winkelmann, 14 years ago

hart and xml-rpc fixes

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