diff --git a/configure b/configure index d1433de50..f8fc6ffad 100755 --- a/configure +++ b/configure @@ -2192,7 +2192,7 @@ ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then - for ac_prog in i686-apple-darwin11-gcc-4.2.1 gcc cc + for ac_prog in gcc cc do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 @@ -2236,7 +2236,7 @@ fi fi if test -z "$CC"; then ac_ct_CC=$CC - for ac_prog in i686-apple-darwin11-gcc-4.2.1 gcc cc + for ac_prog in gcc cc do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 @@ -2908,7 +2908,7 @@ ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu - # Try to avoid LLVM gcc + ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' @@ -3159,7 +3159,7 @@ if test -z "$CXX"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then - for ac_prog in i686-apple-darwin11-g++-4.2.1 g++ + for ac_prog in g++ do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 @@ -3203,7 +3203,7 @@ fi fi if test -z "$CXX"; then ac_ct_CXX=$CXX - for ac_prog in i686-apple-darwin11-g++-4.2.1 g++ + for ac_prog in g++ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 @@ -3512,7 +3512,7 @@ ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu - # Try to avoid LLVM gcc + ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' diff --git a/configure.ac b/configure.ac index e33de9a1e..b08589c2b 100644 --- a/configure.ac +++ b/configure.ac @@ -77,14 +77,14 @@ if test "${LDFLAGS+set}" != set; then fi AC_LANG(C) -AC_PROG_CC([i686-apple-darwin11-gcc-4.2.1 gcc cc]) # Try to avoid LLVM gcc +AC_PROG_CC([gcc cc]) AC_PROG_CPP C_COMPILER=$CC C_PREPROC=$CPP if test "$ENABLE_CPLUSPLUS" = yes; then AC_LANG(C++) - AC_PROG_CXX([i686-apple-darwin11-g++-4.2.1 g++]) # Try to avoid LLVM gcc + AC_PROG_CXX([g++]) AC_PROG_CXXCPP C_COMPILER=$CXX C_PREPROC=$CXXCPP diff --git a/examples/iOS/AccessoryView.xib b/examples/iOS/AccessoryView.xib index 414aa2ce9..1bdf0cc43 100644 --- a/examples/iOS/AccessoryView.xib +++ b/examples/iOS/AccessoryView.xib @@ -2,9 +2,9 @@ 1056 - 10J869 + 10K540 1305 - 1038.35 + 1038.36 461.00 com.apple.InterfaceBuilder.IBCocoaTouchPlugin @@ -197,13 +197,13 @@ key-quote-46x42.png - + 297 - {{593, 2}, {46, 42}} + {{545, 2}, {46, 42}} - + 2 MC42MTE3NjQ3MjkgMC42MDc4NDMxNjA2IDAuNjUwOTgwNDEzAA @@ -213,7 +213,11 @@ IBCocoaTouchFramework 0 0 - + + CourierNewPS-BoldMT + 14 + 16 + STOP @@ -226,13 +230,13 @@ key-stop-46x42.png - + 297 - {{545, 2}, {46, 42}} + {{593, 2}, {46, 42}} - + 2 MC42MTE3NjQ3MjkgMC42MDc4NDMxNjA2IDAuNjUwOTgwNDEzAA @@ -242,22 +246,19 @@ IBCocoaTouchFramework 0 0 - - CourierNewPS-BoldMT - 14 - 16 - - EDIT + + COMMA 2 MC4yMzkyMTU3MDE4IDAuMjM5MjE1NzAxOCAwLjI0MzEzNzI3MDIAA - + NSImage - key-edit-46x42.png + key-comma-46x42.png + @@ -1044,15 +1045,6 @@ 161 - - - touch_up_F13: - - - 7 - - 162 - touch_up_QUOTE: @@ -1071,6 +1063,15 @@ 164 + + + touch_up_COMMA: + + + 7 + + 165 + @@ -1104,7 +1105,6 @@ - @@ -1118,6 +1118,7 @@ + @@ -1160,6 +1161,7 @@ 57 + Button - COMMA 60 @@ -1215,7 +1217,7 @@ 118 - Button + Button - F2 121 @@ -1388,7 +1390,7 @@ - 164 + 165 @@ -1400,6 +1402,7 @@ YES YES + navigation_changed: touch_down: touch_up_COMMA: touch_up_DQUOTE: @@ -1451,12 +1454,14 @@ id id id + id YES YES + navigation_changed: touch_down: touch_up_COMMA: touch_up_DQUOTE: @@ -1484,6 +1489,10 @@ YES + + navigation_changed: + id + touch_down: id @@ -1587,13 +1596,23 @@ YES accessoryView - textView - webView + imageView0 + imageView1 + segmCtrl + textView0 + textView1 + webView0 + webView1 YES UIView + UIImageView + UIImageView + UISegmentedControl UITextView + UITextView + UIWebView UIWebView @@ -1602,8 +1621,13 @@ YES accessoryView - textView - webView + imageView0 + imageView1 + segmCtrl + textView0 + textView1 + webView0 + webView1 YES @@ -1612,11 +1636,31 @@ UIView - textView + imageView0 + UIImageView + + + imageView1 + UIImageView + + + segmCtrl + UISegmentedControl + + + textView0 + UITextView + + + textView1 UITextView - webView + webView0 + UIWebView + + + webView1 UIWebView @@ -1644,8 +1688,8 @@ YES YES + key-comma-46x42.png key-doublequote-46x42.png - key-edit-46x42.png key-f1-46x42.png key-f10-46x42.png key-f11-46x42.png diff --git a/examples/iOS/AppDelegate.m b/examples/iOS/AppDelegate.m index d45f9692f..64a6a71c2 100644 --- a/examples/iOS/AppDelegate.m +++ b/examples/iOS/AppDelegate.m @@ -23,8 +23,6 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( [window addSubview:viewController.view]; [window makeKeyAndVisible]; - viewController.keyboardSounds = -1; - return YES; } @@ -73,7 +71,7 @@ Restart any tasks that were paused (or not yet started) while the the background, optionally refresh the user interface. */ - viewController.keyboardSounds = -1; // delay check of user preferences + [viewController app_become_active]; } diff --git a/examples/iOS/GambitREPL.xcodeproj.tgz b/examples/iOS/GambitREPL.xcodeproj.tgz index c0c7e9637..06c5f9794 100644 Binary files a/examples/iOS/GambitREPL.xcodeproj.tgz and b/examples/iOS/GambitREPL.xcodeproj.tgz differ diff --git a/examples/iOS/Info.plist b/examples/iOS/Info.plist index 722c627ac..d78bed707 100644 --- a/examples/iOS/Info.plist +++ b/examples/iOS/Info.plist @@ -5,7 +5,7 @@ CFBundleDevelopmentRegion en CFBundleDisplayName - Gambit REPL + Gambit REPL dev CFBundleDocumentTypes CFBundleExecutable @@ -28,17 +28,19 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2.0 + 6.0 CFBundleSignature GamC CFBundleURLTypes CFBundleVersion - 2.0 + 6.0 LSRequiresIPhoneOS NSMainNibFile MainWindow + UIFileSharingEnabled + UISupportedInterfaceOrientations UIInterfaceOrientationPortrait diff --git a/examples/iOS/MainWindow.xib b/examples/iOS/MainWindow.xib index 39e4d44d6..09318c5f1 100644 --- a/examples/iOS/MainWindow.xib +++ b/examples/iOS/MainWindow.xib @@ -53,7 +53,7 @@ IBIPadFramework NO - + 292 {768, 1024} @@ -61,8 +61,8 @@ - 3 - MQA + 1 + MSAxIDEAA NO NO @@ -70,19 +70,13 @@ 2 IBIPadFramework + YES + YES YES - - - window - - - - 8 - delegate @@ -99,6 +93,14 @@ 28 + + + rootViewController + + + + 30 + @@ -133,8 +135,8 @@ View Controller - 7 - + 29 + @@ -145,25 +147,23 @@ YES -1.CustomClassName -2.CustomClassName + 29.IBPluginDependency 3.CustomClassName 3.IBPluginDependency 4.CustomClassName 4.IBEditorWindowLastContentRect 4.IBPluginDependency - 7.IBEditorWindowLastContentRect - 7.IBPluginDependency YES UIApplication UIResponder + com.apple.InterfaceBuilder.IBCocoaTouchPlugin AppDelegate com.apple.InterfaceBuilder.IBCocoaTouchPlugin ViewController {{52, 4}, {783, 852}} com.apple.InterfaceBuilder.IBCocoaTouchPlugin - {{289, 4}, {783, 852}} - com.apple.InterfaceBuilder.IBCocoaTouchPlugin @@ -178,7 +178,7 @@ - 28 + 30 @@ -230,6 +230,7 @@ YES YES + navigation_changed: touch_down: touch_up_COMMA: touch_up_DQUOTE: @@ -281,12 +282,14 @@ id id id + id YES YES + navigation_changed: touch_down: touch_up_COMMA: touch_up_DQUOTE: @@ -314,6 +317,10 @@ YES + + navigation_changed: + id + touch_down: id @@ -417,12 +424,16 @@ YES accessoryView - textView - webView + imageView0 + segmCtrl + textView0 + webView0 YES UIView + UIImageView + UISegmentedControl UITextView UIWebView @@ -432,8 +443,10 @@ YES accessoryView - textView - webView + imageView0 + segmCtrl + textView0 + webView0 YES @@ -442,11 +455,19 @@ UIView - textView + imageView0 + UIImageView + + + segmCtrl + UISegmentedControl + + + textView0 UITextView - webView + webView0 UIWebView diff --git a/examples/iOS/ViewController.h b/examples/iOS/ViewController.h index 62e2e2061..33e32476f 100644 --- a/examples/iOS/ViewController.h +++ b/examples/iOS/ViewController.h @@ -10,38 +10,82 @@ // ViewController methods callable from Scheme. -void show_textView(); -void show_webView(); -NSString *get_textView_content(); -void set_textView_font(NSString *name, int size); -void set_textView_content(NSString *str); -void add_output_to_textView(NSString *str); -void add_input_to_textView(NSString *str); -void set_webView_content(NSString *str, BOOL enable_scaling, NSString *mime_type); +void set_navigation(int n); +void show_cancelButton(); +void hide_cancelButton(); +void show_webView(int view); +void show_textView(int view); +void show_imageView(int view); +void set_textView_font(int view, NSString *name, int size); +void set_textView_content(int view, NSString *str); +NSString *get_textView_content(int view); +void add_output_to_textView(int view, NSString *str); +void add_input_to_textView(int view, NSString *str); +void set_webView_content(int view, NSString *str, BOOL enable_scaling, NSString *mime_type); +void set_webView_content_from_file(int view, NSString *path, BOOL enable_scaling, NSString *mime_type); +NSString *eval_js_in_webView(int view, NSString *script); void open_URL(NSString *url); +void segm_ctrl_set_title(int segment, NSString *title); +void segm_ctrl_insert(int segment, NSString *title); void set_pref(NSString *key, NSString *value); NSString *get_pref(NSString *key); +void set_pasteboard(NSString *value); +NSString *get_pasteboard(); +NSString *get_documents_dir(); +void popup_alert(NSString *title, NSString *msg, NSString *cancel_button, NSString *accept_button); +#define NB_WEBVIEWS 4 +#define NB_TEXTVIEWS 2 +#define NB_IMAGEVIEWS 2 -@interface ViewController : UIViewController { +@interface ViewController : UIViewController { - UITextView *textView; + UISegmentedControl *segmCtrl; + UIWebView *webViews[NB_WEBVIEWS]; + UIWebView *webView0; + UIWebView *webView1; + UIWebView *webView2; + UIWebView *webView3; + UITextView *textViews[NB_TEXTVIEWS]; + UITextView *textView0; + UITextView *textView1; + UIImageView *imageViews[NB_IMAGEVIEWS]; + UIImageView *imageView0; + UIImageView *imageView1; + UIButton *cancelButton; UIView *accessoryView; - UIWebView *webView; int keyboardSounds; NSTimer *timer; + NSMutableArray *queuedActions; } -@property (nonatomic, retain) IBOutlet UITextView *textView; +@property (nonatomic, assign) IBOutlet UISegmentedControl *segmCtrl; +@property (nonatomic, assign) IBOutlet UIWebView *webView0; +@property (nonatomic, assign) IBOutlet UIWebView *webView1; +@property (nonatomic, assign) IBOutlet UIWebView *webView2; +@property (nonatomic, assign) IBOutlet UIWebView *webView3; +@property (nonatomic, retain) IBOutlet UITextView *textView0; +@property (nonatomic, retain) IBOutlet UITextView *textView1; +@property (nonatomic, retain) IBOutlet UIImageView *imageView0; +@property (nonatomic, retain) IBOutlet UIImageView *imageView1; +@property (nonatomic, assign) IBOutlet UIButton *cancelButton; @property (nonatomic, assign) IBOutlet UIView *accessoryView; -@property (nonatomic, assign) IBOutlet UIWebView *webView; @property (assign) int keyboardSounds; @property (assign) NSTimer *timer; +@property (assign) NSMutableArray *queuedActions; -- (void)up_key:(NSString*)name; +- (void)queue_action:(void(^)())action; +- (void)send_event:(NSString*)name; +- (void)send_key:(NSString*)name; - (void)heartbeat_tick; - (void)schedule_next_heartbeat_tick:(double)interval; +- (void)app_become_active; + +- (IBAction)navigation_changed:(id)sender; + +- (IBAction)touch_up_cancel:(id)sender; + - (IBAction)touch_down:(id)sender; - (IBAction)touch_up_F1:(id)sender; - (IBAction)touch_up_F2:(id)sender; diff --git a/examples/iOS/ViewController.m b/examples/iOS/ViewController.m index 6c2e6ba7f..e3ab887e9 100644 --- a/examples/iOS/ViewController.m +++ b/examples/iOS/ViewController.m @@ -15,7 +15,7 @@ @implementation ViewController -@synthesize textView, accessoryView, webView, keyboardSounds, timer; +@synthesize segmCtrl, webView0, webView1, webView2, webView3, textView0, textView1, imageView0, imageView1, cancelButton, accessoryView, keyboardSounds, timer, queuedActions; //----------------------------------------------------------------------------- @@ -43,7 +43,7 @@ @implementation ViewController extern char **main_argv; - +___UCS_2 ucs2_gambcdir[1024]; void gambit_setup() { @@ -55,6 +55,8 @@ void gambit_setup() int debug_settings = ___DEBUG_SETTINGS_INITIAL; ___UCS_2STRING *ucs2_argv; + int last_dir_sep; + int i; if (___NONNULLCHARSTRINGLIST_to_NONNULLUCS_2STRINGLIST (main_argv, @@ -62,6 +64,21 @@ void gambit_setup() != ___FIX(___NO_ERR)) exit(1); + last_dir_sep = 0; + i = 0; + + while (ucs2_argv[0][i] != '\0') + { + if (ucs2_argv[0][i] == '/') + last_dir_sep = i; + i++; + } + + for (i=0; isegmCtrl removeTarget:vc action:@selector(navigation_changed:) forControlEvents:UIControlEventValueChanged]; + vc->segmCtrl.selectedSegmentIndex = n; + [vc->segmCtrl addTarget:vc action:@selector(navigation_changed:) forControlEvents:UIControlEventValueChanged]; + } +} - ___disable_heartbeat_interrupts (); + +- (void)queue_action:(void(^)())action { + + [queuedActions addObject:[action copy]]; +} + + +- (void)queue_action_asap:(void(^)())action { + + [self queue_action:action]; + + [self schedule_next_heartbeat_tick:0.0]; +} + + +- (void)send_event:(NSString*)name { + + [self queue_action_asap:^{ send_event(name); }]; +} + + +- (void)send_key:(NSString*)name { + + [self queue_action_asap:^{ send_key(name); }]; } - (void)heartbeat_tick { + [self queue_action:^{ [self schedule_next_heartbeat_tick:heartbeat()]; }]; + ___enable_heartbeat_interrupts (); - ___ON_THROW( + while ([queuedActions count] > 0) { - [self schedule_next_heartbeat_tick:heartbeat()]; - }, - exit(0); - ); + void (^action)(void) = [queuedActions objectAtIndex:0]; + [queuedActions removeObjectAtIndex:0]; + + ___ON_THROW( + { + action(); + }, + exit(0); + ); + } ___disable_heartbeat_interrupts (); } @@ -283,7 +360,7 @@ - (void)heartbeat_tick { - (void)schedule_next_heartbeat_tick:(double)interval { - if (interval > 0) + if (interval >= 0) { if (timer != nil) { @@ -296,121 +373,274 @@ - (void)schedule_next_heartbeat_tick:(double)interval { } -void show_textView() { +- (void)app_become_active { + + theViewController.keyboardSounds = -1; // delay check of user preferences + + [self send_event:@"app-become-active"]; +} + + +void show_cancelButton() { ViewController *vc = theViewController; if (vc != nil) { - [vc.webView resignFirstResponder]; - vc.textView.hidden = NO; - vc.webView.hidden = YES; - [vc.textView becomeFirstResponder]; + vc->cancelButton.hidden = NO; } } -void show_webView() { +void hide_cancelButton() { ViewController *vc = theViewController; if (vc != nil) { - [vc.textView resignFirstResponder]; - vc.webView.hidden = NO; - vc.textView.hidden = YES; - [vc.webView becomeFirstResponder]; + vc->cancelButton.hidden = YES; } } -void set_textView_content(NSString *str) { +void show_webView(int view) { ViewController *vc = theViewController; if (vc != nil) { - vc.textView.text = str; + int i; + + for (int i=0; iwebViews[i] resignFirstResponder]; + vc->webViews[i].hidden = YES; + } + + for (int i=0; itextViews[i] resignFirstResponder]; + vc->textViews[i].hidden = YES; + } + + for (int i=0; iimageViews[i] resignFirstResponder]; + vc->imageViews[i].hidden = YES; + } + + [vc->webViews[view] becomeFirstResponder]; + vc->webViews[view].hidden = NO; } } -NSString *get_textView_content() { +void show_textView(int view) { ViewController *vc = theViewController; if (vc != nil) { - return vc.textView.text; + int i; + + for (int i=0; iwebViews[i] resignFirstResponder]; + vc->webViews[i].hidden = YES; + } + + for (int i=0; itextViews[i] resignFirstResponder]; + vc->textViews[i].hidden = YES; + } + + for (int i=0; iimageViews[i] resignFirstResponder]; + vc->imageViews[i].hidden = YES; + } + + [vc->textViews[view] becomeFirstResponder]; + vc->textViews[view].hidden = NO; } +} - return @""; + +void show_imageView(int view) { + + ViewController *vc = theViewController; + if (vc != nil) + { + int i; + + for (int i=0; iwebViews[i] resignFirstResponder]; + vc->webViews[i].hidden = YES; + } + + for (int i=0; itextViews[i] resignFirstResponder]; + vc->textViews[i].hidden = YES; + } + + for (int i=0; iimageViews[i] resignFirstResponder]; + vc->imageViews[i].hidden = YES; + } + + [vc->imageViews[view] becomeFirstResponder]; + vc->imageViews[view].hidden = NO; + } +} + + +void set_textView_font(int view, NSString *name, int size) { + + ViewController *vc = theViewController; + if (vc != nil) + { + vc->textViews[view].font = [UIFont fontWithName:name size:size]; + } +} + + +void set_textView_content(int view, NSString *str) { + + ViewController *vc = theViewController; + if (vc != nil) + { + vc->textViews[view].text = str; + } } -void set_textView_font(NSString *name, int size) { +NSString *get_textView_content(int view) { ViewController *vc = theViewController; if (vc != nil) { - vc.textView.font = [UIFont fontWithName:name size:size]; + return vc->textViews[view].text; } + + return @""; } -void add_to_textView(NSString *str) { +void add_to_textView(int view, NSString *str) { ViewController *vc = theViewController; if (vc != nil) { - NSMutableString *new_text = [vc.textView.text mutableCopy]; + NSMutableString *new_text = [vc->textViews[view].text mutableCopy]; [new_text appendString:str]; - vc.textView.text = new_text; + vc->textViews[view].text = new_text; [new_text release]; } } -void add_output_to_textView(NSString *str) { +void add_output_to_textView(int view, NSString *str) { - add_to_textView([str stringByReplacingOccurrencesOfString:@" " withString:@"\u2007"]); + add_to_textView(view, [str stringByReplacingOccurrencesOfString:@" " withString:@"\u2007"]); } -void add_input_to_textView(NSString *str) { +void add_input_to_textView(int view, NSString *str) { ViewController *vc = theViewController; if (vc != nil) { - NSMutableString *new_text = [vc.textView.text mutableCopy]; - NSRange selectedRange = vc.textView.selectedRange; + NSMutableString *new_text = [vc->textViews[view].text mutableCopy]; + NSRange selectedRange = vc->textViews[view].selectedRange; [new_text replaceCharactersInRange:selectedRange withString:str]; - vc.textView.text = new_text; + vc->textViews[view].text = new_text; [new_text release]; } } -void set_webView_content(NSString *str, BOOL enable_scaling, NSString *mime_type) { +void set_webView_content(int view, NSString *str, BOOL enable_scaling, NSString *mime_type) { ViewController *vc = theViewController; if (vc != nil) { - [vc.webView + [vc->webViews[view] loadData:[str dataUsingEncoding:NSUnicodeStringEncoding] MIMEType:mime_type textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]] ]; - vc.webView.scalesPageToFit = enable_scaling; + vc->webViews[0].scalesPageToFit = enable_scaling; + } +} + + +void set_webView_content_from_file(int view, NSString *path, BOOL enable_scaling, NSString *mime_type) { + + ViewController *vc = theViewController; + if (vc != nil) + { + NSString *p = [[NSBundle mainBundle] pathForResource:path ofType:nil]; + if (p != nil) + { + NSData *data = [NSData dataWithContentsOfFile:p]; + if (data != nil) + { + [vc->webViews[view] + loadData:data + MIMEType:mime_type + textEncodingName:@"UTF-8" + baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]] + ]; + vc->webViews[view].scalesPageToFit = enable_scaling; + } + } } } +NSString *eval_js_in_webView(int view, NSString *script) { + + ViewController *vc = theViewController; + if (vc != nil) + { + return [vc->webViews[view] stringByEvaluatingJavaScriptFromString:script]; + } + + return nil; +} + void open_URL(NSString *url) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; } +void segm_ctrl_set_title(int segment, NSString *title) { + + ViewController *vc = theViewController; + if (vc != nil) + { + [vc->segmCtrl setTitle:title forSegmentAtIndex:segment]; + } +} + + +void segm_ctrl_insert(int segment, NSString *title) { + + ViewController *vc = theViewController; + if (vc != nil) + { + [vc->segmCtrl insertSegmentWithTitle:title atIndex:segment animated:true]; + } +} + + void set_pref(NSString *key, NSString *value) { NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; @@ -426,49 +656,118 @@ void set_pref(NSString *key, NSString *value) { } +void set_pasteboard(NSString *value) { + + UIPasteboard *pb = [UIPasteboard generalPasteboard]; + pb.string = value; +} + + +NSString *get_pasteboard() { + + UIPasteboard *pb = [UIPasteboard generalPasteboard]; + return pb.string; +} + + +NSString *get_documents_dir() { + + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + return [paths objectAtIndex:0]; +} + + +void popup_alert(NSString *title, NSString *msg, NSString *cancel_button, NSString *accept_button) { + + UIAlertView *alert = [[UIAlertView alloc] + initWithTitle: title + message: msg + delegate: theViewController + cancelButtonTitle: cancel_button + otherButtonTitles: accept_button, nil]; + [alert show]; + [alert release]; +} + + +// Called when an alertview button is touched +- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { + + NSString *event; + + switch (buttonIndex) { + + case 1: + event = @"popup-alert-accept"; + break; + + default: + case 0: + event = @"popup-alert-cancel"; + break; + } + + [self send_event:event]; +} + + +#pragma mark - +#pragma mark Toolbar action + +- (IBAction)navigation_changed:(id)sender { + int n = segmCtrl.selectedSegmentIndex; + if (n >= 0) + [self send_event:[NSString stringWithFormat:@"NAV%d", n]]; +} + + +#pragma mark - +#pragma mark Cancel button action + +- (IBAction)touch_up_cancel:(id)sender { + [self send_event:@"cancel"]; +} + + - (BOOL)textView:(UITextView *)textView2 shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text hasSuffix:@"\n"]) { unichar c; - int end = [textView.text length]; + int end = [textViews[0].text length]; int line_start = range.location+range.length; while (line_start > 0 && - (c = [textView.text characterAtIndex:line_start-1]) != '\n' && + (c = [textViews[0].text characterAtIndex:line_start-1]) != '\n' && c != 0x2007) // non breaking space line_start--; int line_end = range.location+range.length; while (line_end < end && - [textView.text characterAtIndex:line_end] != '\n') + [textViews[0].text characterAtIndex:line_end] != '\n') line_end++; - NSString *line = [textView.text substringWithRange:NSMakeRange(line_start, line_end-line_start)]; - - if (line_end == end) + if (line_start == line_end) { - add_to_textView(text); - - ___enable_heartbeat_interrupts (); + [textViews[0] resignFirstResponder]; // Hide the keyboard after "return" key is pressed on empty line + } + else + { + NSString *line = [textViews[0].text substringWithRange:NSMakeRange(line_start, line_end-line_start)]; - ___ON_THROW( + if (line_end == end) { - [self schedule_next_heartbeat_tick:send_input([line stringByAppendingString:text])]; - }, - exit(0); - ); - - ___disable_heartbeat_interrupts (); - -#if 0 - [textView resignFirstResponder]; // Hide the keyboard after "return" key is pressed -#endif + add_to_textView(0, text); + + [self queue_action_asap:^{ + send_input([line stringByAppendingString:text]); + }]; + } + else + add_to_textView(0, line); } - else - add_to_textView(line); return NO; } @@ -479,7 +778,7 @@ - (BOOL)textView:(UITextView *)textView2 shouldChangeTextInRange:(NSRange)range - (IBAction)touch_up_Char:(id)sender withString:(NSString *)aString { - add_input_to_textView(aString); + add_input_to_textView(0, aString); } @@ -511,7 +810,7 @@ - (IBAction)touch_down:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F1:(id)sender { - [self up_key:@"F1"]; + [self send_key:@"F1"]; } @@ -519,7 +818,7 @@ - (IBAction)touch_up_F1:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F2:(id)sender { - [self up_key:@"F2"]; + [self send_key:@"F2"]; } @@ -527,7 +826,7 @@ - (IBAction)touch_up_F2:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F3:(id)sender { - [self up_key:@"F3"]; + [self send_key:@"F3"]; } @@ -535,7 +834,7 @@ - (IBAction)touch_up_F3:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F4:(id)sender { - [self up_key:@"F4"]; + [self send_key:@"F4"]; } @@ -543,7 +842,7 @@ - (IBAction)touch_up_F4:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F5:(id)sender { - [self up_key:@"F5"]; + [self send_key:@"F5"]; } @@ -551,7 +850,7 @@ - (IBAction)touch_up_F5:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F6:(id)sender { - [self up_key:@"F6"]; + [self send_key:@"F6"]; } @@ -559,7 +858,7 @@ - (IBAction)touch_up_F6:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F7:(id)sender { - [self up_key:@"F7"]; + [self send_key:@"F7"]; } @@ -567,7 +866,7 @@ - (IBAction)touch_up_F7:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F8:(id)sender { - [self up_key:@"F8"]; + [self send_key:@"F8"]; } @@ -575,7 +874,7 @@ - (IBAction)touch_up_F8:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F9:(id)sender { - [self up_key:@"F9"]; + [self send_key:@"F9"]; } @@ -583,7 +882,7 @@ - (IBAction)touch_up_F9:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F10:(id)sender { - [self up_key:@"F10"]; + [self send_key:@"F10"]; } @@ -591,7 +890,7 @@ - (IBAction)touch_up_F10:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F11:(id)sender { - [self up_key:@"F11"]; + [self send_key:@"F11"]; } @@ -599,7 +898,7 @@ - (IBAction)touch_up_F11:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F12:(id)sender { - [self up_key:@"F12"]; + [self send_key:@"F12"]; } @@ -607,7 +906,7 @@ - (IBAction)touch_up_F12:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_F13:(id)sender { - [self up_key:@"F13"]; + [self send_key:@"F13"]; } @@ -615,7 +914,7 @@ - (IBAction)touch_up_F13:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_SHARP:(id)sender { - [self up_key:@"#"]; + [self send_key:@"#"]; } @@ -623,7 +922,7 @@ - (IBAction)touch_up_SHARP:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_DQUOTE:(id)sender { - [self up_key:@"\""]; + [self send_key:@"\""]; } @@ -631,7 +930,7 @@ - (IBAction)touch_up_DQUOTE:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_QUOTE:(id)sender { - [self up_key:@"'"]; + [self send_key:@"'"]; } @@ -639,7 +938,7 @@ - (IBAction)touch_up_QUOTE:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_COMMA:(id)sender { - [self up_key:@","]; + [self send_key:@","]; } @@ -647,7 +946,7 @@ - (IBAction)touch_up_COMMA:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_PLUS:(id)sender { - [self up_key:@"+"]; + [self send_key:@"+"]; } @@ -655,7 +954,7 @@ - (IBAction)touch_up_PLUS:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_MINUS:(id)sender { - [self up_key:@"-"]; + [self send_key:@"-"]; } @@ -663,7 +962,7 @@ - (IBAction)touch_up_MINUS:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_STAR:(id)sender { - [self up_key:@"*"]; + [self send_key:@"*"]; } @@ -671,7 +970,7 @@ - (IBAction)touch_up_STAR:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_SLASH:(id)sender { - [self up_key:@"/"]; + [self send_key:@"/"]; } @@ -679,7 +978,7 @@ - (IBAction)touch_up_SLASH:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_LPAREN:(id)sender { - [self up_key:@"("]; + [self send_key:@"("]; } @@ -687,7 +986,7 @@ - (IBAction)touch_up_LPAREN:(id)sender { #pragma mark Accessory view action - (IBAction)touch_up_RPAREN:(id)sender { - [self up_key:@")"]; + [self send_key:@")"]; } @@ -697,16 +996,7 @@ - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *) if ([url hasPrefix:@"event:"]) { - ___enable_heartbeat_interrupts (); - - ___ON_THROW( - { - [self schedule_next_heartbeat_tick:send_event([url stringByAppendingString:@"\n"])]; - }, - exit(0); - ); - - ___disable_heartbeat_interrupts (); + [self send_event:url]; return NO; } @@ -720,8 +1010,22 @@ - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *) - (void)dealloc { + int i; + [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:nil]; - [textView release]; + + [segmCtrl release]; + + for (i=0; i YES + IBProxyObject + IBUIBarButtonItem + IBUIImageView + IBUIToolbar + IBUIButton IBUIWebView IBUITextView + IBUISegmentedControl IBUIView - IBProxyObject YES @@ -43,17 +48,61 @@ 292 YES - + - 274 - {768, 1004} + -2147483374 + {768, 960} - + 1 MSAxIDEAA + YES + IBIPadFramework + + + + -2147483374 + {768, 960} + + + + + YES + IBIPadFramework + + + + -2147483374 + {768, 960} + + + + + YES + IBIPadFramework + + + + -2147483374 + {768, 960} + + + + + YES + IBIPadFramework + + + + -2147483374 + {768, 960} + + + + YES YES IBIPadFramework @@ -65,26 +114,169 @@ IBCocoaTouchFramework - + -2147483374 - {768, 1004} + {768, 960} - + + YES YES IBIPadFramework + NO + + + 1 + 1 + IBCocoaTouchFramework + + + + + -2147483356 + {768, 960} + + + + 1 + NO + IBIPadFramework + + + + -2147483356 + {768, 960} + + + + 1 + NO + IBIPadFramework + + + + 266 + + YES + + + 292 + {{234, 8}, {300, 30}} + + + + NO + IBIPadFramework + 2 + 4 + 0 + + YES + REPL + Wiki + Help + Edit + + + YES + + + + + + + YES + + + + + + + YES + {0, 0} + {0, 0} + {0, 0} + {0, 0} + + + YES + + + + + + + + {{0, 960}, {768, 44}} + + + + NO + NO + IBIPadFramework + + YES + + IBIPadFramework + + 5 + + + IBIPadFramework + 300 + + + + + IBIPadFramework + + 5 + + + + + + -2147483359 + {{732, 2}, {32, 32}} + + + + NO + 0.60000002384185791 + IBIPadFramework + 0 + 0 + + Helvetica-Bold + 15 + 16 + + YES + + 3 + MQA + + + 1 + MC4xOTYwNzg0MzQ2IDAuMzA5ODAzOTMyOSAwLjUyMTU2ODY1NgA + + + 3 + MC41AA + + + NSImage + button-cancel.png + {{0, 20}, {768, 1004}} - - - 3 - MQA - + + NO YES @@ -104,37 +296,151 @@ 23 + + + delegate + + + + 28 + delegate - 24 + 68 - textView + textView0 - 25 + 70 + + + + navigation_changed: + + + 13 + + 75 - webView + segmCtrl + + + + 76 + + + + imageView0 + + + + 80 + + + + webView0 - 27 + 85 delegate - + - 28 + 88 + + + + delegate + + + + 90 + + + + delegate + + + + 92 + + + + webView1 + + + + 93 + + + + webView2 + + + + 94 + + + + webView3 + + + + 95 + + + + cancelButton + + + + 96 + + + + touch_up_cancel: + + + 7 + + 97 + + + + delegate + + + + 99 + + + + textView1 + + + + 100 + + + + imageView1 + + + + 102 @@ -162,8 +468,16 @@ YES - + + + + + + + + + @@ -171,11 +485,90 @@ 22 + Text View 0 26 + Web View 0 + + + 46 + + + YES + + + + + + + + 49 + + + + + 63 + + + YES + + + + + + 62 + + + + + 64 + + + + + 77 + + + Image View 0 + + + 86 + + + Cancel Button + + + 87 + + + Web View 1 + + + 89 + + + Web View 2 + + + 91 + + + Web View 3 + + + 98 + + + Text View 1 + + + 101 + + + Image View 1 @@ -185,17 +578,36 @@ YES -1.CustomClassName -2.CustomClassName + 101.IBPluginDependency 2.IBEditorWindowLastContentRect 2.IBPluginDependency 22.IBPluginDependency 22.IBViewBoundsToFrameTransform 26.IBPluginDependency 26.IBViewBoundsToFrameTransform + 46.IBPluginDependency + 49.IBPluginDependency + 62.IBPluginDependency + 62.IUISegmentedControlInspectorSelectedSegmentMetadataKey + 64.IBPluginDependency + 77.IBPluginDependency + 86.IBPluginDependency + 86.IBUIButtonInspectorSelectedEdgeInsetMetadataKey + 86.IBUIButtonInspectorSelectedStateConfigurationMetadataKey + 87.IBPluginDependency + 87.IBViewBoundsToFrameTransform + 89.IBPluginDependency + 89.IBViewBoundsToFrameTransform + 91.IBPluginDependency + 91.IBViewBoundsToFrameTransform + 98.IBPluginDependency + 98.IBViewBoundsToFrameTransform YES ViewController UIResponder + com.apple.InterfaceBuilder.IBCocoaTouchPlugin {{247, 4}, {783, 852}} com.apple.InterfaceBuilder.IBCocoaTouchPlugin com.apple.InterfaceBuilder.IBCocoaTouchPlugin @@ -206,6 +618,31 @@ P4AAAL+AAABCLAAAw4mAAA + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + P4AAAL+AAABCLAAAw4mAAA + + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + P4AAAL+AAABCLAAAw4mAAA + + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + P4AAAL+AAABCLAAAw4mAAA + + com.apple.InterfaceBuilder.IBCocoaTouchPlugin + + P4AAAL+AAADDj4AAxEVAAA + @@ -220,7 +657,7 @@ - 28 + 102 @@ -232,6 +669,7 @@ YES YES + navigation_changed: touch_down: touch_up_COMMA: touch_up_DQUOTE: @@ -256,6 +694,7 @@ touch_up_SHARP: touch_up_SLASH: touch_up_STAR: + touch_up_cancel: YES @@ -283,12 +722,15 @@ id id id + id + id YES YES + navigation_changed: touch_down: touch_up_COMMA: touch_up_DQUOTE: @@ -313,9 +755,14 @@ touch_up_SHARP: touch_up_SLASH: touch_up_STAR: + touch_up_cancel: YES + + navigation_changed: + id + touch_down: id @@ -412,6 +859,10 @@ touch_up_STAR: id + + touch_up_cancel: + id + @@ -419,13 +870,29 @@ YES accessoryView - textView - webView + cancelButton + imageView0 + imageView1 + segmCtrl + textView0 + textView1 + webView0 + webView1 + webView2 + webView3 YES UIView + UIButton + UIImageView + UIImageView + UISegmentedControl UITextView + UITextView + UIWebView + UIWebView + UIWebView UIWebView @@ -434,8 +901,16 @@ YES accessoryView - textView - webView + cancelButton + imageView0 + imageView1 + segmCtrl + textView0 + textView1 + webView0 + webView1 + webView2 + webView3 YES @@ -444,11 +919,43 @@ UIView - textView + cancelButton + UIButton + + + imageView0 + UIImageView + + + imageView1 + UIImageView + + + segmCtrl + UISegmentedControl + + + textView0 + UITextView + + + textView1 UITextView - webView + webView0 + UIWebView + + + webView1 + UIWebView + + + webView2 + UIWebView + + + webView3 UIWebView @@ -472,6 +979,10 @@ YES 3 + + button-cancel.png + {64, 64} + 300 diff --git a/examples/iOS/build-gambit-iOS b/examples/iOS/build-gambit-iOS index f70d8382a..f774e0aa1 100644 --- a/examples/iOS/build-gambit-iOS +++ b/examples/iOS/build-gambit-iOS @@ -84,11 +84,12 @@ select_ios() esac - export CC="$ios_platform_dir/Developer/usr/bin/gcc -isysroot $ios_sdk_dir -arch $arch" - export CXX="$ios_platform_dir/Developer/usr/bin/g++ -isysroot $ios_sdk_dir -arch $arch" + export PATH="$ios_platform_dir/Developer/usr/bin:$PATH" + export CC="gcc -isysroot $ios_sdk_dir -arch $arch" + export CXX="g++ -isysroot $ios_sdk_dir -arch $arch" export CFLAGS="-Wno-trigraphs -Wreturn-type -Wunused-variable -I$gambit_prefix/include -L$gambit_prefix/lib" export CXXFLAGS="$CFLAGS" - export LD="$ios_platform_dir/Developer/usr/bin/ld -arch $arch" + export LD="ld -arch $arch" export LDFLAGS="" } diff --git a/examples/iOS/button-abc.png b/examples/iOS/button-abc.png new file mode 100644 index 000000000..2b28e7027 Binary files /dev/null and b/examples/iOS/button-abc.png differ diff --git a/examples/iOS/button-cancel.png b/examples/iOS/button-cancel.png new file mode 100644 index 000000000..aa545eb65 Binary files /dev/null and b/examples/iOS/button-cancel.png differ diff --git a/examples/iOS/button-compass.png b/examples/iOS/button-compass.png new file mode 100644 index 000000000..7048380f1 Binary files /dev/null and b/examples/iOS/button-compass.png differ diff --git a/examples/iOS/button-empty.png b/examples/iOS/button-empty.png new file mode 100644 index 000000000..6af7df077 Binary files /dev/null and b/examples/iOS/button-empty.png differ diff --git a/examples/iOS/button-left-left.png b/examples/iOS/button-left-left.png new file mode 100644 index 000000000..a8aa7b8aa Binary files /dev/null and b/examples/iOS/button-left-left.png differ diff --git a/examples/iOS/button-left.png b/examples/iOS/button-left.png new file mode 100644 index 000000000..3eafab2c3 Binary files /dev/null and b/examples/iOS/button-left.png differ diff --git a/examples/iOS/button-question.png b/examples/iOS/button-question.png new file mode 100644 index 000000000..fab9a4006 Binary files /dev/null and b/examples/iOS/button-question.png differ diff --git a/examples/iOS/button-right-right.png b/examples/iOS/button-right-right.png new file mode 100644 index 000000000..cec98e0a4 Binary files /dev/null and b/examples/iOS/button-right-right.png differ diff --git a/examples/iOS/button-right.png b/examples/iOS/button-right.png new file mode 100644 index 000000000..376c5dcc8 Binary files /dev/null and b/examples/iOS/button-right.png differ diff --git a/examples/iOS/button-up-arrow.png b/examples/iOS/button-up-arrow.png new file mode 100644 index 000000000..ce6fabc8f Binary files /dev/null and b/examples/iOS/button-up-arrow.png differ diff --git a/examples/iOS/button-up.png b/examples/iOS/button-up.png new file mode 100644 index 000000000..387ad5a51 Binary files /dev/null and b/examples/iOS/button-up.png differ diff --git a/examples/iOS/gambit-c.html b/examples/iOS/gambit-c.html new file mode 100644 index 000000000..c636a2e5d --- /dev/null +++ b/examples/iOS/gambit-c.html @@ -0,0 +1,19641 @@ + + + + +Gambit-C, a portable implementation of Scheme + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Back: Gambit-CForward: 1.1 Accessing the system files   FastBack: Gambit-CUp: Gambit-CFastForward: 2. The Gambit Scheme interpreterTop: Gambit-CContents: Table of ContentsIndex: General index
+ + +

Gambit-C

+ + + +
+ +
[View PDF version]
+ +

This manual documents Gambit-C. It covers release v4.6.1. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: Gambit-CForward: 1.1 Accessing the system files   FastBack: Gambit-CUp: Gambit-CFastForward: 2. The Gambit Scheme interpreterTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

1. The Gambit-C system

+ + + + + + +

The Gambit programming system is a full implementation of the Scheme +language which conforms to the R4RS, R5RS and IEEE Scheme standards. It +consists of two main programs: gsi, the Gambit Scheme +interpreter, and gsc, the Gambit Scheme compiler. +

+

Gambit-C is a version of the Gambit programming system in which the +compiler generates portable C code, making the whole Gambit-C system and +the programs compiled with it easily portable to many computer +architectures for which a C compiler is available. With appropriate +declarations in the source code the executable programs generated by +the compiler run roughly as fast as equivalent C programs. +

+

For the most up to date information on Gambit and add-on packages +please check the Gambit web page at +http://gambit.iro.umontreal.ca. The web page has links to the +Gambit mailing list, the bug reporting system, and the source code +repository. +

+ + + + +
+ + + + + + + + + + + +
Back: 1. The Gambit-C systemForward: 2. The Gambit Scheme interpreter   FastBack: 1. The Gambit-C systemUp: 1. The Gambit-C systemFastForward: 2. The Gambit Scheme interpreterTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

1.1 Accessing the system files

+ +

Files related to Gambit, such as executables, libraries and header files, +are stored in multiple Gambit installation directories. +Gambit may be installed on a system according to two different +installation models. +

+

In the first model there is a single directory where all the Gambit +installation directories are stored. This central installation +directory is typically /usr/local/Gambit-C under UNIX, +/Library/Gambit-C under Mac OS X and C:/Program +Files/Gambit-C under Microsoft Windows. This may have been +overridden when the system was built with the command configure +--prefix=/my/Gambit-C. If the system was built with the command +configure --enable-multiple-versions then the central +installation directory is prefix/version, where +version is the system version string +(e.g. v4.6.1 for Gambit v4.6.1). Moreover, +prefix/current will be a symbolic link which points to +the central installation directory. In this model, the Gambit +installation directory named X is simply the subdirectory +X of the central installation directory. +

+

In the second model some or all of the Gambit installation directories +are stored in installation specific directories. The location of +these directories is assigned when the system is built using the +command configure --bindir=/my/bin --includedir=/my/include +--libdir=/my/lib. +

+

The advantage of the first model is that it is easy to have multiple +versions of Gambit coexist and to remove all the files of a given +version. However, the second model may be necessary to conform to the +package installation conventions of some operating systems. +

+

Executable programs such as the interpreter gsi and compiler +gsc can be found in the bin installation directory. +Adding this directory to the PATH environment variable allows +these programs to be started by simply entering their name. This is +done automatically by the Mac OS X and Microsoft Windows installers. +

+

The runtime library is located in the lib installation +directory. When the system’s runtime library is built as a +shared-library (with the command configure --enable-shared) all +programs built with Gambit-C, including the interpreter and compiler, +need to find this library when they are executed and consequently this +directory must be in the path searched by the system for +shared-libraries. This path is normally specified through an +environment variable which is LD_LIBRARY_PATH on most versions +of UNIX, LIBPATH on AIX, SHLIB_PATH on HPUX, +DYLD_LIBRARY_PATH on Mac OS X, and PATH on Microsoft +Windows. If the shell is sh, the setting of the path can be +made for a single execution by prefixing the program name with the +environment variable assignment, as in: +

+
 
$ LD_LIBRARY_PATH=/usr/local/Gambit-C/lib gsi
+
+ +

A similar problem exists with the Gambit header file gambit.h, +located in the include installation directory. This header +file is needed for compiling Scheme programs with the Gambit-C +compiler. When the C compiler is being called explicitly it may be +necessary to use a -I<dir> command line option to +indicate where to find header files and a -L<dir> command +line option to indicate where to find libraries. +

+

Access to both of these files can be simplified by creating a link to +them in the appropriate system directories (special privileges may +however be required): +

+
 
$ ln -s /usr/local/Gambit-C/lib/libgambc.a /usr/lib # name may vary
+$ ln -s /usr/local/Gambit-C/include/gambit.h /usr/include
+
+ +

Alternatively these files can be copied or linked in the directory +where the C compiler is invoked (this requires no special privileges). +

+

Another approach is to set some environment variables which +are used to tell the C compiler where to find header files +and libraries. For example, the following settings can be +used for the gcc C compiler: +

+
 
$ export LIBRARY_PATH=/usr/local/Gambit-C/lib
+$ export CPATH=/usr/local/Gambit-C/include
+
+ +

Note that this may have been done by the installation process. In +particular, the Mac OS X and Microsoft Windows prebuilt installers set +up the environment so that the gcc compiler finds these files +automatically. +

+ +
+ + + + + + + + + + + +
Back: 1.1 Accessing the system filesForward: 2.1 Interactive mode   FastBack: 1. The Gambit-C systemUp: Gambit-CFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2. The Gambit Scheme interpreter

+ + +

Synopsis: +

+
 
gsi [-:runtimeoption,…] [-i] [-f] [-v] [[-] [-e expressions] [file]]…
+
+ + +

The interpreter is executed in interactive mode when no file or +- or -e option is given on the command line. Otherwise +the interpreter is executed in batch mode. The -i option +is ignored by the interpreter. The initialization file will be +examined unless the -f option is present (see section Customization). The -v option prints the system version +string, system time stamp, operating system type, and configure script +options on standard output and exits. Runtime options are explained +in Runtime options. +

+ + + + + + + + +
+ + + + + + + + + + + +
Back: 2. The Gambit Scheme interpreterForward: 2.2 Batch mode   FastBack: 2. The Gambit Scheme interpreterUp: 2. The Gambit Scheme interpreterFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.1 Interactive mode

+ +

In interactive mode a read-eval-print loop (REPL) is started for the +user to interact with the interpreter. At each iteration of this loop +the interpreter displays a prompt, reads a command and executes it. +The commands can be expressions to evaluate (the typical case) +or special commands related to debugging, for example ,q to +terminate the process (for a complete list of commands see +Debugging). Most commands produce some output, such as the +value or error message resulting from an evaluation. +

+

The input and output of the interaction is done on the +interaction channel. The interaction channel can be specified +through the runtime options but if none is specified the system uses a +reasonable default that depends on the system’s configuration. When +the system’s runtime library was built with support for GUIDE, the +Gambit Universal IDE (with the command configure +--enable-guide) the interaction channel corresponds to the +console window of the primordial thread (for details see +GUIDE), otherwise the interaction channel is the user’s +console, also known as the controlling terminal in the +UNIX world. When the REPL starts, the ports associated with +(current-input-port), (current-output-port) and +(current-error-port) all refer to the interaction channel. +

+

Expressions are evaluated in the global interaction environment. +The interpreter adds to this environment any definition entered using +the define and define-macro +special forms. Once the evaluation of an expression is completed, the +value or values resulting from the evaluation are output to the +interaction channel by the pretty printer. The special “void” +object is not output. This object is returned by most procedures and +special forms which the Scheme standard defines as returning an +unspecified value (e.g. write, set!, define). +

+

Here is a sample interaction with gsi: +

+
 
$ gsi
+Gambit v4.6.1
+
+> (define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))
+> (map fact '(1 2 3 4 5 6))
+(1 2 6 24 120 720)
+> (values (fact 10) (fact 40))
+3628800
+815915283247897734345611269596115894272000000000
+> ,q
+
+ +

What happens when errors occur is explained in Debugging. +

+
+ + + + + + + + + + + +
Back: 2.1 Interactive modeForward: 2.3 Customization   FastBack: 2. The Gambit Scheme interpreterUp: 2. The Gambit Scheme interpreterFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.2 Batch mode

+ +

In batch mode the command line arguments denote files to be loaded, +REPL interactions to start (- option), and expressions to be +evaluated (-e option). Note that the - and -e +options can be interspersed with the files on the command line and can +occur multiple times. The interpreter processes the command line +arguments from left to right, loading files with the load +procedure and evaluating expressions with the eval procedure in +the global interaction environment. After this processing the +interpreter exits. +

+

When the file name has no extension the load procedure first +attempts to load the file with no extension as a Scheme source file. +If that file doesn’t exist it will search for both a source file and +an object file. The object file’s name is obtained by adding to the +file name a .on extension with the highest consecutive +version number starting with 1. The source file’s name is obtained by +adding to the file name the file extensions .scm and +.six (the first found is the source file). If both a source +file and an object file exist, then the one with the latest +modification time is loaded. Otherwise the file that is found is +loaded. When the file name has an extension, the load +procedure will only attempt to load the file with that specific name. +

+

When the extension of the file loaded is .scm the content of +the file will be parsed using the normal Scheme prefix syntax. When +the extension of the file loaded is .six the content of the +file will be parsed using the Scheme infix syntax extension (see +Scheme infix syntax extension). Otherwise, gsi will +parse the file using the normal Scheme prefix syntax. +

+

The ports associated with (current-input-port), +(current-output-port) and (current-error-port) initially +refer respectively to the standard input (stdin), standard +output (stdout) and the standard error (stderr) of the +interpreter. This is true even in REPLs started with the - +option. The usual interaction channel (console or IDE’s console +window) is still used to read expressions and commands and to display +results. This makes it possible to use REPLs to debug programs which +read the standard input and write to the standard output, even when +these have been redirected. +

+

Here is a sample use of the interpreter in batch mode, under UNIX: +

+
 
$ cat h.scm
+(display "hello") (newline)
+$ cat w.six
+display("world"); newline();
+$ gsi h.scm - w.six -e "(pretty-print 1)(pretty-print 2)"
+hello
+> (define (display x) (write (reverse (string->list x))))
+> ,(c 0)
+(#\d #\l #\r #\o #\w)
+1
+2
+
+ +
+ + + + + + + + + + + +
Back: 2.2 Batch modeForward: 2.4 Process exit status   FastBack: 2. The Gambit Scheme interpreterUp: 2. The Gambit Scheme interpreterFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.3 Customization

+ +

There are two ways to customize the interpreter. When the interpreter +starts off it tries to execute a (load "~~lib/gambcext") (for an +explanation of how file names are interpreted see Host environment). +An error is not signaled when the file does not exist. Interpreter +extensions and patches that are meant to apply to all users and all +modes should go in that file. +

+

Extensions which are meant to apply to a single user or to a specific +working directory are best placed in the initialization file, +which is a file containing Scheme code. In all modes, the interpreter +first tries to locate the initialization file by searching the following +locations: ‘.gambcini’ and ‘~/.gambcini’ (with no extension, a +.scm extension, and a .six extension in that order). The +first file that is found is examined as though the expression +(include initialization-file) had been entered at the +read-eval-print loop where initialization-file is the file that +was found. Note that by using an include the macros defined in +the initialization file will be visible from the read-eval-print loop +(this would not have been the case if load had been used). The +initialization file is not searched for or examined when the -f +option is specified. +

+
+ + + + + + + + + + + +
Back: 2.3 CustomizationForward: 2.5 Scheme scripts   FastBack: 2. The Gambit Scheme interpreterUp: 2. The Gambit Scheme interpreterFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.4 Process exit status

+ +

The status is zero when the interpreter exits normally and is nonzero +when the interpreter exits due to an error. Here is the meaning of +the exit statuses: +

+
+
0
+

The execution of the primordial thread (i.e. the main thread) did not +encounter any error. It is however possible that other threads +terminated abnormally (by default threads other than the primordial +thread terminate silently when they raise an exception that is not +handled). +

+
+
64
+

The runtime options or the environment variable GAMBCOPT +contained a syntax error or were invalid. +

+
+
70
+

This normally indicates that an exception was raised in the primordial +thread and the exception was not handled. +

+
+
71
+

There was a problem initializing the runtime system, for example +insufficient memory to allocate critical tables. +

+
+
+ +

For example, if the shell is sh: +

+
 
$ gsi -:d0 -e "(pretty-print (expt 2 100))"
+1267650600228229401496703205376
+$ echo $?
+0
+$ gsi -:d0,unknown # try to use an unknown runtime option
+$ echo $?
+64
+$ gsi -:d0 nonexistent.scm # try to load a file that does not exist
+$ echo $?
+70
+$ gsi nonexistent.scm
+*** ERROR IN ##main -- No such file or directory
+(load "nonexistent.scm")
+$ echo $?
+70
+
+ +
 
$ gsi -:m4000000 # ask for a 4 gigabyte heap
+*** malloc: vm_allocate(size=528384) failed (error code=3)
+*** malloc[15068]: error: Can't allocate region
+$ echo $?
+71
+
+ +

Note the use of the runtime option -:d0 that prevents error +messages from being output, and the runtime option -:m4000000 +which sets the minimum heap size to 4 gigabytes. +

+
+ + + + + + + + + + + +
Back: 2.4 Process exit statusForward: 2.5.1 Scripts under UNIX and Mac OS X   FastBack: 2. The Gambit Scheme interpreterUp: 2. The Gambit Scheme interpreterFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.5 Scheme scripts

+ +

The load procedure treats specially files that begin with the +two characters #! and @;. Such files are called +script files and the first line is called the script line. +In addition to indicating that the file is a script, the script line +provides information about the source code language to be used by the +load procedure. After the two characters #! and +@; the system will search for the first substring matching one +of the following language specifying tokens: +

+
+
scheme-r4rs
+
+

R4RS language with prefix syntax, case-insensitivity, keyword syntax +not supported +

+
+
scheme-r5rs
+
+

R5RS language with prefix syntax, case-insensitivity, keyword syntax +not supported +

+
+
scheme-ieee-1178-1990
+
+

IEEE 1178-1990 language with prefix syntax, case-insensitivity, keyword +syntax not supported +

+
+
scheme-srfi-0
+
+

R5RS language with prefix syntax and SRFI 0 support +(i.e. cond-expand special form), case-insensitivity, keyword +syntax not supported +

+
+
gsi-script
+
+

Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword +syntax supported +

+
+
gsc-script
+
+

Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword +syntax supported +

+
+
six-script
+
+

Full Gambit Scheme language with infix syntax, case-sensitivity, keyword +syntax supported +

+
+
+ +

If a language specifying token is not found, load will use the +same language as a nonscript file (i.e. it uses the file extension and +runtime system options to determine the language). +

+

After processing the script line, load will parse the rest of +the file (using the syntax of the language indicated) and then execute +it. When the file is being loaded because it is an argument on the +interpreter’s command line, the interpreter will: +

+ + + + + + + + +
+ + + + + + + + + + + +
Back: 2.5 Scheme scriptsForward: 2.5.2 Scripts under Microsoft Windows   FastBack: 2. The Gambit Scheme interpreterUp: 2.5 Scheme scriptsFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.5.1 Scripts under UNIX and Mac OS X

+ +

Under UNIX and Mac OS X, the Gambit-C installation process creates the +executable gsi and also the executables six, +gsi-script, six-script, scheme-r5rs, +scheme-srfi-0, etc as links to gsi. A Scheme script +need only start with the name of the desired Scheme language variant +prefixed with #! and the directory where the Gambit-C +executables are stored. This script should be made executable by +setting the execute permission bits (with a chmod +x +script). Here is an example of a script which lists on standard +output the files in the current directory: +

+
 
#!/usr/local/Gambit-C/bin/gsi-script
+(for-each pretty-print (directory-files))
+
+ +

Here is another UNIX script, using the Scheme infix syntax extension, +which takes a single integer argument and prints on standard output the +numbers from 1 to that integer: +

+
 
#!/usr/local/Gambit-C/bin/six-script
+
+void main (obj n_str)
+{
+  int n = \string->number(n_str);
+  for (int i=1; i<=n; i++)
+    \pretty-print(i);
+}
+
+ +

For maximal portability it is a good idea to start scripts indirectly +through the /usr/bin/env program, so that the executable of the +interpreter will be searched in the user’s PATH. This is what +SRFI 22 recommends. For example here is a script that mimics the UNIX +cat utility for text files: +

+
 
#!/usr/bin/env gsi-script
+
+(define (display-file filename)
+  (display (call-with-input-file filename
+             (lambda (port)
+               (read-line port #f)))))
+
+(for-each display-file (cdr (command-line)))
+
+ +
+ + + + + + + + + + + +
Back: 2.5.1 Scripts under UNIX and Mac OS XForward: 2.5.3 Compiling scripts   FastBack: 2. The Gambit Scheme interpreterUp: 2.5 Scheme scriptsFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.5.2 Scripts under Microsoft Windows

+ +

Under Microsoft Windows, the Gambit-C installation process creates the +executable gsi.exe and six.exe and also the batch files +gsi-script.bat, six-script.bat, scheme-r5rs.bat, +scheme-srfi-0.bat, etc which simply invoke gsi.exe with +the same command line arguments. A Scheme script need only start with +the name of the desired Scheme language variant prefixed with +@;. A UNIX script can be converted to a Microsoft Windows +script simply by changing the script line and storing the script in a +file whose name has a .bat or .cmd extension: +

+
 
@;gsi-script %~f0 %*
+(display "files:\n")
+(pretty-print (directory-files))
+
+ +

Note that Microsoft Windows always searches executables in the user’s +PATH, so there is no need for an indirection such as the UNIX +/usr/bin/env. However the script line must end with %~f0 +%* to pass the expanded filename of the script and command line +arguments to the interpreter. +

+
+ + + + + + + + + + + +
Back: 2.5.2 Scripts under Microsoft WindowsForward: 3. The Gambit Scheme compiler   FastBack: 2. The Gambit Scheme interpreterUp: 2.5 Scheme scriptsFastForward: 3. The Gambit Scheme compilerTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

2.5.3 Compiling scripts

+ +

A script file can be compiled using the Gambit Scheme compiler +(see section The Gambit Scheme compiler) into a standalone executable. The script line will +provide information to the compiler on which language to use. The +script line also provides information on which runtime options to use +when executing the compiled script. This is useful to set the default +runtime options of an executable program. +

+

The compiled script will be executed similarly to an interpreted +script (i.e. the list of command line arguments returned by the +command-line procedure and the invocation of the main +procedure). +

+

For example: +

+
 
$ cat square.scm
+#!/usr/local/Gambit-C/bin/gsi-script -:d0
+(define (main arg)
+  (pretty-print (expt (string->number arg) 2)))
+$ gsi square 30        # gsi will load square.scm
+900
+$ gsc -exe square      # compile the script to a standalone program
+$ ./square 30
+900
+$ ./square 1 2 3       # too many arguments to main
+$ echo $?
+70
+$ ./square -:d1 1 2 3  # ask for error message
+*** ERROR -- Wrong number of arguments passed to procedure
+(main "1" "2" "3")
+
+ +
+ + + + + + + + + + + +
Back: 2.5.3 Compiling scriptsForward: 3.1 Interactive mode   FastBack: 2. The Gambit Scheme interpreterUp: Gambit-CFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3. The Gambit Scheme compiler

+ + + +

Synopsis: +

+
 
gsc [-:runtimeoption,…] [-i] [-f] [-v]
+    [-prelude expressions] [-postlude expressions]
+    [-dynamic] [-exe] [-obj] [-cc-options options]
+    [-ld-options-prelude options] [-ld-options options]
+    [-warnings] [-verbose] [-report] [-expansion] [-gvm]
+    [-debug] [-debug-location] [-debug-source]
+    [-debug-environments] [-track-scheme]
+    [-o output] [-c] [-keep-c] [-link] [-flat] [-l base]
+    [[-] [-e expressions] [file]]…
+
+ + + + + + + + + +
+ + + + + + + + + + + +
Back: 3. The Gambit Scheme compilerForward: 3.2 Customization   FastBack: 3. The Gambit Scheme compilerUp: 3. The Gambit Scheme compilerFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.1 Interactive mode

+ +

When no command line argument is present other than options the +compiler behaves like the interpreter in interactive mode. The only +difference with the interpreter is that the compilation related +procedures listed in this chapter are also available +(i.e. compile-file, compile-file-to-c, etc). +

+
+ + + + + + + + + + + +
Back: 3.1 Interactive modeForward: 3.3 Batch mode   FastBack: 3. The Gambit Scheme compilerUp: 3. The Gambit Scheme compilerFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.2 Customization

+ +

Like the interpreter, the compiler will examine the initialization +file unless the -f option is specified. +

+
+ + + + + + + + + + + +
Back: 3.2 CustomizationForward: 3.4 Link files   FastBack: 3. The Gambit Scheme compilerUp: 3. The Gambit Scheme compilerFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.3 Batch mode

+ + + + + + + + +

In batch mode gsc takes a set of file names (with either no +extension, or a C file extension, or some other extension) on the +command line and compiles each Scheme file into a C file. +The recognized C file extensions are .c, .C, .cc, +.cp, .cpp, .CPP, .cxx, .c++, +.m, .M, and .mm. +The extension can be omitted from file when the Scheme file has a +.scm or .six extension. When the extension of the +Scheme file is .six the content of the file will be parsed +using the Scheme infix syntax extension (see Scheme infix syntax extension). Otherwise, gsc will parse the Scheme file using the +normal Scheme prefix syntax. Files with a C file extension must +have been previously produced by gsc, with the -c option, +and are used by Gambit’s linker. +

+

For each Scheme file a C file file.c will be produced. +The C file’s name is the same as the Scheme file, but the extension is +changed to .c. By default the C file is created in the same +directory as the Scheme file. This default can be overridden with the +compiler’s -o option. +

+

The C files produced by the compiler serve two purposes. They will be +processed by a C compiler to generate object files, and they also +contain information to be read by Gambit’s linker to generate a +link file. The link file is a C file that collects various +linking information for a group of modules, such as the set of all +symbols and global variables used by the modules. + + +The linker is only invoked when the -link or -exe +options appear on the command line. +

+

Compiler options must be specified before the first file name and +after the -: runtime option (see section Runtime options). If +present, the -i, -f, and -v compiler options +must come first. The available options are: +

+ + +
+
-i
+

Force interpreter mode. +

+
-f
+

Do not examine the initialization file. +

+
-v
+

Print the system version string, system time stamp, operating system +type, and configure script options on standard output and exit. +

+
-prelude expressions
+

Add expressions to the top of the source code being compiled. +

+
-postlude expressions
+

Add expressions to the bottom of the source code being compiled. +

+
-cc-options options
+

Add options to the command that invokes the C compiler. +

+
-ld-options-prelude options
+

Add options to the command that invokes the C linker. +

+
-ld-options options
+

Add options to the command that invokes the C linker. +

+
-warnings
+

Display warnings. +

+
-verbose
+

Display a trace of the compiler’s activity. +

+
-report
+

Display a global variable usage report. +

+
-expansion
+

Display the source code after expansion. +

+
-gvm
+

Generate a listing of the GVM code. +

+
-debug
+

Include all debugging information in the code generated. +

+
-debug-location
+

Include source code location debugging information in the code generated. +

+
-debug-source
+

Include the source code debugging information in the code generated. +

+
-debug-environments
+

Include environment debugging information in the code generated. +

+
-track-scheme
+

Generate #line directives referring back to the Scheme code. +

+
-o output
+

Set name of output file or directory where output file(s) are written. +

+
-dynamic
+

Compile Scheme source files to dynamically loadable object +files (this is the default). +

+
-exe
+

Compile Scheme source files into an executable program. +

+
-obj
+

Compile Scheme source files to object files. +

+
-keep-c
+

Keep any intermediate .c files that are generated. +

+
-c
+

Compile Scheme source files to C without generating link file. +

+
-link
+

Compile Scheme source files to C and generate a link file. +

+
-flat
+

Generate a flat link file instead of the default incremental link file. +

+
-l base
+

Specify the link file of the base library to use for the link. +

+
-
+

Start REPL interaction. +

+
-e expressions
+

Evaluate expressions in the interaction environment. +

+
+ + +

The -i option forces the compiler to process the remaining +command line arguments like the interpreter. +

+ +

The -prelude option adds the specified expressions to the top of +the source code being compiled. The main use of this option is to +supply declarations on the command line. For example the following +invocation of the compiler will compile the file bench.scm in +unsafe mode: +

+
 
$ gsc -prelude "(declare (not safe))" bench.scm
+
+ + +

The -postlude option adds the specified expressions to the bottom +of the source code being compiled. The main use of this option is to +supply the expression that will start the execution of the program. For +example: +

+
 
$ gsc -postlude "(start-bench)" bench.scm
+
+ + +

The -cc-options option is only meaningful when a dynamically +loadable object file is being generated (neither the -c or +-link options are used). The -cc-options option adds +the specified options to the command that invokes the C compiler. The +main use of this option is to specify the include path, some symbols +to define or undefine, the optimization level, or any C compiler +option that is different from the default. For example: +

+
 
$ gsc -cc-options "-U___SINGLE_HOST -O2 -I../include" bench.scm
+
+ + + +

The -ld-options-prelude and -ld-options options are only +meaningful when a dynamically loadable object file is being generated +(neither the -c or -link options are used). The +-ld-options-prelude and -ld-options options add the +specified options to the command that invokes the C linker (the +options in ld-options-prelude are passed to the C linker before +the input file and the options in ld-options are passed after). +The main use of this option is to specify additional object files or +libraries that need to be linked, or any C linker option that is +different from the default (such as the library search path and flags +to select between static and dynamic linking). For example: +

+
 
$ gsc -ld-options "-L/usr/X11R6/lib -lX11 -dynamic" bench.scm
+
+ + +

The -warnings option displays on standard output all warnings +that the compiler may have. +

+ +

The -verbose option displays on standard output a trace of the +compiler’s activity. +

+ +

The -report option displays on standard output a global +variable usage report. Each global variable used in the program is +listed with 4 flags that indicate whether the global variable is +defined, referenced, mutated and called. +

+ +

The -expansion option displays on standard output the source code +after expansion and inlining by the front end. +

+ +

The -gvm option generates a listing of the intermediate code +for the “Gambit Virtual Machine” (GVM) of each Scheme file on +file.gvm. +

+ + +

The -debug option causes all kinds of debugging information to +be saved in the code generated. See the documentation of the +debug declaration for details. +

+ + +

The -debug-location option causes source code location +debugging information to be saved in the code generated. See the +documentation of the debug-location declaration for details. +

+ + +

The -debug-source option causes source code debugging +information to be saved in the code generated. See the documentation +of the debug-source declaration for details. +

+ + +

The -debug-environments option causes environment debugging +information to be saved in the code generated. See the documentation +of the debug-environments declaration for details. +

+ +

The -track-scheme options causes the generation of #line +directives that refer back to the Scheme source code. This allows the +use of a C debugger or profiler to debug Scheme code. +

+ +

The -o option sets the filename of the output file, or the +directory in which the output file(s) generated by the compiler are +written. +

+ + + + + + + +

If the -link or -exe options appear on the command line, +the Gambit linker is invoked to generate the link file from the set of +C files specified on the command line or produced by the Gambit +compiler. By default the link file is last_.c, where +last.c is the last file in the set of C files. When the +-c option is specified, the Scheme source files are compiled to +C files. When the -exe option is specified, the generated C +files and link file are compiled and linked using the C compiler to +produce an executable program whose name defaults to +last.exe. When the -obj option is specified, the +generated C files are compiled using the C compiler to produce object +files (.o or .obj extensions). If neither the +-link, -c, -exe, -obj options appear on +the command line, the Scheme source files are compiled to dynamically +loadable object files (.on extension). The +-keep-c option will prevent the deletion of any intermediate +.c file that is generated. Note that in this case the +intermediate .c file will be generated in the same directory as +the Scheme source file even if the -o option is used. +

+ +

The -flat option is only meaningful when a link file is being +generated (i.e. the -link or -exe options also appear on +the command line). The -flat option directs the Gambit linker +to generate a flat link file. By default, the linker generates an +incremental link file (see the next section for a description of the +two types of link files). +

+ +

The -l option is only meaningful when an incremental link file +is being generated (i.e. the -link or -exe options +appear on the command line and the -flat option is absent). +The -l option specifies the link file (without the .c +extension) of the base library to use for the incremental link. By +default the link file of the Gambit runtime library is used +(i.e. ~~lib/_gambc.c). +

+ +

The - option starts a REPL interaction. +

+ +

The -e option evaluates the specified expressions in the +interaction environment. +

+
+ + + + + + + + + + + +
Back: 3.3 Batch modeForward: 3.4.1 Building an executable program   FastBack: 3. The Gambit Scheme compilerUp: 3. The Gambit Scheme compilerFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.4 Link files

+ +

Gambit can be used to create programs and libraries of Scheme +modules. This section explains the steps required to do so and the role +played by the link files. +

+

In general, a program is composed of a set of Scheme modules and C +modules. Some of the modules are part of the Gambit runtime library and +the other modules are supplied by the user. When the program is +started it must setup various global tables (including the symbol table +and the global variable table) and then sequentially execute the Scheme +modules (more or less as though they were being loaded one after another). +The information required for this is contained in one or more link +files generated by the Gambit linker from the C files produced by the +Gambit compiler. +

+

The order of execution of the Scheme modules corresponds to the order of +the modules on the command line which produced the link file. The order +is usually important because most modules define variables and +procedures which are used by other modules (for this reason the +program’s main computation is normally started by the last module). +

+

When a single link file is used to contain the linking information of +all the Scheme modules it is called a flat link file. Thus a +program built with a flat link file contains in its link file both +information on the user modules and on the runtime library. This is +fine if the program is to be statically linked but is wasteful in +a shared-library context because the linking information of the +runtime library can’t be shared and will be duplicated in all +programs (this linking information typically takes hundreds of kilobytes). +

+

Flat link files are mainly useful to bundle multiple Scheme modules to +make a runtime library (such as the Gambit runtime library) or to make a +single file that can be loaded with the load procedure. +

+

An incremental link file contains only the linking information +that is not already contained in a second link file (the “base” link +file). Assuming that a flat link file was produced when the runtime +library was linked, a program can be built by linking the user +modules with the runtime library’s link file, producing an incremental +link file. This allows the creation of a shared-library which +contains the modules of the runtime library and its flat link file. +The program is dynamically linked with this shared-library and +only contains the user modules and the incremental link file. For +small programs this approach greatly reduces the size of the +program because the incremental link file is small. A “hello +world” program built this way can be as small as 5 Kbytes. Note that +it is perfectly fine to use an incremental link file for statically +linked programs (there is very little loss compared to a single flat +link file). +

+

Incremental link files may be built from other incremental link files. +This allows the creation of shared-libraries which extend the +functionality of the Gambit runtime library. +

+ + + + + + + +
+ + + + + + + + + + + +
Back: 3.4 Link filesForward: 3.4.2 Building a loadable library   FastBack: 3. The Gambit Scheme compilerUp: 3.4 Link filesFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.4.1 Building an executable program

+ +

The simplest way to create an executable program is to invoke +gsc with the -exe option. The compiler will +transparently perform all the steps necessary, including compiling +Scheme source files to C files, generating the link file, compiling +the C files generated to object files, and creating the final +executable file using the C linker. The following example shows how +to build the executable program hello.exe which contains the +two Scheme modules h.scm and w.six. +

+
 
$ cat h.scm
+(display "hello") (newline)
+$ cat w.six
+display("world"); newline();
+$ gsc -o hello.exe -exe h.scm w.six
+h.scm:
+/Users/feeley/gambit/doc/h.c:
+w.six:
+/Users/feeley/gambit/doc/w.c:
+/Users/feeley/gambit/doc/w_.c:
+$ ./hello.exe
+hello
+world
+
+ +

The detailed steps which are performed can be viewed by setting the +GAMBC_CC_VERBOSE environment variable to a nonnull value. For +example: +

+
 
$ export GAMBC_CC_VERBOSE=yes
+$ gsc -o hello.exe -exe h.scm w.six
+h.scm:
+/Users/feeley/gambit/doc/h.c:
+gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
+ -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
+ -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "h.o" h.c
+w.six:
+/Users/feeley/gambit/doc/w.c:
+gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
+ -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
+ -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w.o" w.c
+/Users/feeley/gambit/doc/w_.c:
+gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
+ -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
+ -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w_.o" w_.c
+gcc  -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
+ -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
+ -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include"
+ -o "hello.exe" h.o w.o w_.o "/usr/local/Gambit-C/lib/libgambc.a"
+
+ +

Using a single invocation of gsc with the -exe option is +sometimes inappropriate when the build process is more complex, for +example when the program is composed of several seperately compiled +modules. In such a case it is useful to decompose the build process +into smaller compilation steps. The hello.exe executable +program could have been built by seperating the generation of C files +from the C compilation and linking: +

+
 
$ gsc -c h.scm
+$ gsc -c w.six
+$ gsc -o hello.exe -exe h.c w.c
+
+ +

When even finer control is desired the build process can be decomposed +into smaller steps that invoke the C compiler and linker explicitly. +This is described in the rest of this section. +

+

The gsc compiler can be invoked to compile each Scheme module +into a C file and to create an incremental link file. The C files and +the link file must then be compiled with a C compiler and linked (at +the object file level) with the Gambit runtime library and possibly +other libraries (such as the math library and the dynamic loading +library). +

+

Here is for example how a program with three modules (one in C and two +in Scheme) can be built. The content of the three source files (m1.c, +m2.scm and m3.scm) is: +

+
 
/* File: "m1.c" */
+int power_of_2 (int x) { return 1<<x; }
+
+; File: "m2.scm"
+(c-declare "extern int power_of_2 ();")
+(define pow2 (c-lambda (int) int "power_of_2"))
+(define (twice x) (cons x x))
+
+; File: "m3.scm"
+(write (map twice (map pow2 '(1 2 3 4)))) (newline)
+
+ +

The compilation of the two Scheme source files can be done with +three invocations of gsc: +

+
 
$ gsc -c m2.scm        # create m2.c (note: .scm is optional)
+$ gsc -c m3.scm        # create m3.c (note: .scm is optional)
+$ gsc -link m2.c m3.c  # create the incremental link file m3_.c
+
+ +

Alternatively, the three invocations of gsc can be replaced by a +single invocation: +

+
 
$ gsc -link m2 m3
+m2:
+m3:
+
+ +

At this point there will be 4 C files: m1.c, m2.c, +m3.c, and m3_.c. To produce an executable program these +files must be compiled with a C compiler and linked with the Gambit-C +runtime library. The C compiler options needed will depend on the C +compiler and the operating system (in particular it may be necessary +to add the options -I/usr/local/Gambit-C/include +-L/usr/local/Gambit-C/lib to access the gambit.h header file +and the Gambit-C runtime library). +

+

Here is an example under Mac OS X: +

+
 
$ uname -srmp
+Darwin 8.1.0 Power Macintosh powerpc
+$ gsc -obj m1.c m2.c m3.c m3_.c
+m1.c:
+m2.c:
+m3.c:
+m3_.c:
+$ gcc m1.o m2.o m3.o m3_.o -lgambc
+$ ./a.out
+((2 . 2) (4 . 4) (8 . 8) (16 . 16))
+
+ +

Here is an example under Linux: +

+
 
$ uname -srmp
+Linux 2.6.8-1.521 i686 athlon
+$ gsc -obj m1.c m2.c m3.c m3_.c
+m1.c:
+m2.c:
+m3.c:
+m3_.c:
+$ gcc m1.o m2.o m3.o m3_.o -lgambc -lm -ldl -lutil
+$ ./a.out
+((2 . 2) (4 . 4) (8 . 8) (16 . 16))
+
+ +
+ + + + + + + + + + + +
Back: 3.4.1 Building an executable programForward: 3.4.3 Building a shared-library   FastBack: 3. The Gambit Scheme compilerUp: 3.4 Link filesFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.4.2 Building a loadable library

+ + +

To bundle multiple modules into a single object file that can be +dynamically loaded with the load procedure, a flat link file is +needed. The compiler’s -o option must be used to name the C +file generated as follows. If the dynamically loadable object file is +to be named myfile.on then the -o option +must set the name of the link file generated to +myfile.on.c (note that the .c extension +could also be .cc, .cpp or whatever extension is +appropriate for C/C++ source files). The three modules of the +previous example can be bundled by generating a link file in this way: +

+
 
$ gsc -link -flat -o foo.o1.c m2 m3
+m2:
+m3:
+*** WARNING -- "cons" is not defined,
+***            referenced in: ("m2.c")
+*** WARNING -- "map" is not defined,
+***            referenced in: ("m3.c")
+*** WARNING -- "newline" is not defined,
+***            referenced in: ("m3.c")
+*** WARNING -- "write" is not defined,
+***            referenced in: ("m3.c")
+
+ +

The warnings indicate that there are no definitions (defines or +set!s) of the variables cons, map, newline +and write in the set of modules being linked. Before +foo.o1 is loaded, these variables will have to be bound; either +implicitly (by the runtime library) or explicitly. +

+

When compiling the C files and link file generated, the flag +-D___DYNAMIC must be passed to the C compiler and the C +compiler and linker must be told to generate a dynamically loadable +shared library. +

+

Here is an example under Mac OS X: +

+
 
$ uname -srmp
+Darwin 10.5.0 i386 i386
+$ gsc -link -flat -o foo.o1.c m2 m3 > /dev/null
+m2:
+m3:
+$ gsc -cc-options "-D___DYNAMIC" -obj m1.c m2.c m3.c foo.o1.c
+m1.c:
+m2.c:
+m3.c:
+foo.o1.c:
+$ gcc -bundle m1.o m2.o m3.o foo.o1.o -o foo.o1
+$ gsi foo.o1
+((2 . 2) (4 . 4) (8 . 8) (16 . 16))
+
+ +

Here is an example under Linux: +

+
 
$ uname -srmp
+Linux 2.6.8-1.521 i686 athlon
+$ gsc -link -flat -o foo.o1.c m2 m3 > /dev/null
+m2:
+m3:
+$ gsc -cc-options "-D___DYNAMIC" -obj m1.c m2.c m3.c foo.o1.c
+m1.c:
+m2.c:
+m3.c:
+foo.o1.c:
+$ gcc -shared m1.o m2.o m3.o foo.o1.o -o foo.o1
+$ gsi foo.o1
+((2 . 2) (4 . 4) (8 . 8) (16 . 16))
+
+ +

Here is a more complex example, under Solaris, which shows how to build +a loadable library mymod.o1 composed of the files m4.scm, +m5.scm and x.c that links to system shared libraries (for +X-windows): +

+
 
$ uname -srmp
+SunOS ungava 5.6 Generic_105181-05 sun4m sparc SUNW,SPARCstation-20
+$ gsc -link -flat -o mymod.o1.c m4 m5
+m4:
+m5:
+*** WARNING -- "*" is not defined,
+***            referenced in: ("m4.c")
+*** WARNING -- "+" is not defined,
+***            referenced in: ("m5.c")
+*** WARNING -- "display" is not defined,
+***            referenced in: ("m5.c" "m4.c")
+*** WARNING -- "newline" is not defined,
+***            referenced in: ("m5.c" "m4.c")
+*** WARNING -- "write" is not defined,
+***            referenced in: ("m5.c")
+$ gsc -cc-options "-D___DYNAMIC" -obj m4.c m5.c x.c mymod.o1.c
+m4.c:
+m5.c:
+x.c:
+mymod.o1.c:
+$ /usr/ccs/bin/ld -G -o mymod.o1 mymod.o1.o m4.o m5.o x.o -lX11 -lsocket
+$ gsi mymod.o1
+hello from m4
+hello from m5
+(f1 10) = 22
+$ cat m4.scm
+(define (f1 x) (* 2 (f2 x)))
+(display "hello from m4")
+(newline)
+
+(c-declare #<<c-declare-end
+#include "x.h"
+c-declare-end
+)
+(define x-initialize (c-lambda (char-string) bool "x_initialize"))
+(define x-display-name (c-lambda () char-string "x_display_name"))
+(define x-bell (c-lambda (int) void "x_bell"))
+$ cat m5.scm
+(define (f2 x) (+ x 1))
+(display "hello from m5")
+(newline)
+
+(display "(f1 10) = ")
+(write (f1 10))
+(newline)
+
+(x-initialize (x-display-name))
+(x-bell 50) ; sound the bell at 50%
+$ cat x.c
+#include <X11/Xlib.h>
+
+static Display *display;
+
+int x_initialize (char *display_name)
+{
+  display = XOpenDisplay (display_name);
+  return display != NULL;
+}
+
+char *x_display_name (void)
+{
+  return XDisplayName (NULL);
+}
+
+void x_bell (int volume)
+{
+  XBell (display, volume);
+  XFlush (display);
+}
+$ cat x.h
+int x_initialize (char *display_name);
+char *x_display_name (void);
+void x_bell (int);
+
+ +
+ + + + + + + + + + + +
Back: 3.4.2 Building a loadable libraryForward: 3.4.4 Other compilation options   FastBack: 3. The Gambit Scheme compilerUp: 3.4 Link filesFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.4.3 Building a shared-library

+ + + + +

A shared-library can be built using an incremental link file or a flat +link file. An incremental link file is normally used when the Gambit +runtime library (or some other library) is to be extended with new +procedures. A flat link file is mainly useful when building a +“primal” runtime library, which is a library (such as the Gambit +runtime library) that does not extend another library. When compiling +the C files and link file generated, the flags -D___LIBRARY and +-D___SHARED must be passed to the C compiler. The flag +-D___PRIMAL must also be passed to the C compiler when a primal +library is being built. +

+

A shared-library mylib.so containing the two first modules of +the previous example can be built this way: +

+
 
$ uname -srmp
+Linux bailey 1.2.13 #2 Wed Aug 28 16:29:41 GMT 1996 i586
+$ gsc -link -o mylib.c m2
+$ gsc -obj -cc-options "-D___SHARED" m1.c m2.c mylib.c
+m1.c:
+m2.c:
+mylib.c:
+$ gcc -shared  m1.o m2.o mylib.o -o mylib.so
+
+ +

Note that this shared-library is built using an incremental link file +(it extends the Gambit runtime library with the procedures pow2 +and twice). This shared-library can in turn be used to build +an executable program from the third module of the previous example: +

+
 
$ gsc -link -l mylib m3
+$ gsc -obj m3.c m3_.c
+m3.c:
+m3_.c:
+$ gcc m3.o m3_.o mylib.so -lgambc
+$ LD_LIBRARY_PATH=.:/usr/local/lib ./a.out
+((2 . 2) (4 . 4) (8 . 8) (16 . 16))
+
+ +
+ + + + + + + + + + + +
Back: 3.4.3 Building a shared-libraryForward: 3.5 Procedures specific to compiler   FastBack: 3. The Gambit Scheme compilerUp: 3.4 Link filesFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.4.4 Other compilation options

+ + + +

The performance of the code can be increased by passing the +-D___SINGLE_HOST flag to the C compiler. This will merge all +the procedures of a module into a single C procedure, which reduces +the cost of intra-module procedure calls. In addition the -O +option can be passed to the C compiler. For large modules, it will +not be practical to specify both -O and -D___SINGLE_HOST +for typical C compilers because the compile time will be high and the +C compiler might even fail to compile the program for lack of memory. +It has been observed that lower levels of optimization (e.g. -O1) +often give faster compilation and also generate faster code. It is +a good idea to experiment. +

+ + +

Normally C compilers will not automatically search +/usr/local/Gambit-C/include for header files so the flag +-I/usr/local/Gambit-C/include should be passed to the C +compiler. Similarly, C compilers/linkers will not automatically +search /usr/local/Gambit-C/lib for libraries so the flag +-L/usr/local/Gambit-C/lib should be passed to the C +compiler/linker. Alternatives are given in Accessing the system files. +

+ + + + + + + + + + +

A variety of flags are needed by some C compilers when compiling a +shared-library or a dynamically loadable library. Some of these flags +are: -shared, -call_shared, -rdynamic, +-fpic, -fPIC, -Kpic, -KPIC, -pic, ++z, -G. Check your compiler’s documentation to see +which flag you need. +

+
+ + + + + + + + + + + +
Back: 3.4.4 Other compilation optionsForward: 4. Runtime options   FastBack: 3. The Gambit Scheme compilerUp: 3. The Gambit Scheme compilerFastForward: 4. Runtime optionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

3.5 Procedures specific to compiler

+ +

The Gambit Scheme compiler features the following procedures that +are not available in the Gambit Scheme interpreter. +

+
(compile-file-to-c file [options: options] [output: output] [module-name: module-name])procedure
+ + +

The file parameter must be a string naming an existing file +containing Scheme source code. The extension can be omitted from +file when the Scheme file has a .scm or .six +extension. This procedure compiles the source file into a file +containing C code. By default, this file is named after file +with the extension replaced with .c. The name of the generated +file can be specified with the output parameter. If +output is a string naming a directory then the C file is created +in that directory. Otherwise the name of the C file is output. +The name of the generated module can be specified with the +module-name parameter. If module-name is #f or is +not specified, then the name of the module is derived from the name of +the C file generated, without the extension. +

+

Compilation options are specified through the options parameter +which must be a list of symbols. Any combination of the following +options can be used: verbose, report, expansion, +gvm, and debug. +

+

When the compilation is successful, compile-file-to-c returns +the name of the C file generated. When there is a compilation error, +#f is returned. +

+
 
$ cat h.scm
+(display "hello") (newline)
+$ gsc
+Gambit v4.6.1
+
+> (compile-file-to-c "h")
+"/Users/feeley/gambit/doc/h.c"
+
+ + +
(compile-file file [options: options] [output: output] [cc-options: cc-options] [ld-options-prelude: ld-options-prelude] [ld-options: ld-options])procedure
+ + + + +

The file, options, and output parameters have the +same meaning as for the compile-file-to-c procedure, except that +file may be a Scheme source file or a +C file possibly generated by the Gambit Scheme compiler (for example +with the compile-file-to-c procedure). The +cc-options parameter is a string containing the options to pass +to the C compiler and the ld-options-prelude and +ld-options parameters are strings containing the options to pass +to the C linker (the options in ld-options-prelude are passed to +the C linker before the input file and the options in ld-options +are passed after). +

+

The compile-file procedure compiles the source file file +into an object file, which is either a file dynamically loadable using +the load procedure, or a C linkable object file destined to be +linked with the C linker (for example to create a standalone +executable program). The presence of the +obj option in options will cause the creation of a C +linkable object file and therefore the options +ld-options-prelude and ld-options are ignored, otherwise a +dynamically loadable file is created. In both cases, if file is +a Scheme source file, the compiler first compiles file to a C +file which is created in the same directory as file regardless +of the output parameter. Then the C file is compiled with the C +compiler. +

+

When the compilation is successful, compile-file returns the +name of the object file generated. When there is a compilation error, +#f is returned. +

+

The name of the object file can be specified with the output +parameter. If output is a string naming a directory then the +object file is created in that directory. Otherwise the name of the +object file is output. +

+

In the case of a dynamically loadable object file, by default the +object file is named after file with the extension replaced with +.on, where n is a positive integer that acts as a +version number. The next available version number is generated +automatically by compile-file. +

+

When dynamically loaded object files are loaded using the load +procedure, the .on extension can be specified (to select +a particular version) or omitted (to load the file with a +.on extension with the highest n consecutively from +1). When the .on extension is not specified and older +versions are no longer needed, all versions must be deleted and the +compilation must be repeated (this is necessary because the file name, +including the extension, is used to name some of the exported symbols +of the object file). +

+

Note that dynamically loadable object files can only be generated on +host operating systems that support dynamic loading. +

+
 
$ cat h.scm
+(display "hello") (newline)
+$ gsc
+Gambit v4.6.1
+
+> (compile-file "h")
+"/Users/feeley/gambit/doc/h.o1"
+> (load "h")
+hello
+"/Users/feeley/gambit/doc/h.o1"
+> (compile-file-to-c "h" output: "h.o99.c")
+"/Users/feeley/gambit/doc/h.o99.c"
+> (compile-file "h.o99.c")
+"/Users/feeley/gambit/doc/h.o99"
+> (load "h.o99")
+hello
+"/Users/feeley/gambit/doc/h.o99"
+> (compile-file-to-c "h")
+"/Users/feeley/gambit/doc/h.c"
+> (compile-file "h.c" options: '(obj))
+"/Users/feeley/gambit/doc/h.o"
+
+ + + +
(link-incremental module-list [output: output] [base: base] [warnings?: warnings?])procedure
+ + +

The first parameter must be a non empty list of strings naming Scheme +modules to link (the file extension may be omitted). An incremental link +file is generated for the modules specified in module-list. By +default the link file generated is named last_.c, where +last is the name of the last module, without the file extension. +The name of the generated +link file can be specified with the output parameter. If +output is a string naming a directory then the link file is +created in that directory. Otherwise the name of the link file is +output. +

+

The base link file is specified by the base parameter, which +must be a string. By default the base link file is the Gambit runtime +library link file ~~lib/_gambc.c. However, when base is +supplied it is the name of the base link file (the file extension +may be omitted). +

+

The warnings? parameter controls whether warnings are +generated for undefined references. +

+

The following example shows how to build the executable program +hello which contains the two Scheme modules h.scm and +w.six. +

+
 
$ uname -srmp
+Darwin 8.1.0 Power Macintosh powerpc
+$ cat h.scm
+(display "hello") (newline)
+$ cat w.six
+display("world"); newline();
+$ gsc
+Gambit v4.6.1
+
+> (compile-file-to-c "h")
+"/Users/feeley/gambit/doc/h.c"
+> (compile-file-to-c "w")
+"/Users/feeley/gambit/doc/w.c"
+> (link-incremental '("h" "w") output: "hello.c")
+"/Users/feeley/gambit/doc/hello_.c"
+> ,q
+$ gsc -obj h.c w.c hello.c
+h.c:
+w.c:
+hello.c:
+$ gcc h.o w.o hello.o -lgambc -o hello
+$ ./hello
+hello
+world
+
+ + + +
(link-flat module-list [output: output] [warnings?: warnings?])procedure
+ + +

The first parameter must be a non empty list of strings naming Scheme +modules to link (the file extension may be omitted). The first string +must be the name of a Scheme module +or the name of a link file and the remaining strings must name Scheme +modules. A flat link file +is generated for the modules specified in module-list. By +default the link file generated is named last_.c, where +last is the name of the last module. The name of the generated +link file can be specified with the output parameter. If +output is a string naming a directory then the link file is +created in that directory. Otherwise the name of the link file is +output. If a dynamically loadable object file is produced from +the link file output, then the name of the dynamically +loadable object file must be output stripped of its file +extension. +

+

The warnings? parameter controls whether warnings are +generated for undefined references. +

+

The following example shows how to build the dynamically loadable object +file lib.o1 which contains the two Scheme modules +m6.scm and m7.scm. +

+
 
$ uname -srmp
+Darwin 8.1.0 Power Macintosh powerpc
+$ cat m6.scm
+(define (f x) (g (* x x)))
+$ cat m7.scm
+(define (g y) (+ n y))
+$ gsc
+Gambit v4.6.1
+
+> (compile-file-to-c "m6")
+"/Users/feeley/gambit/doc/m6.c"
+> (compile-file-to-c "m7")
+"/Users/feeley/gambit/doc/m7.c"
+> (link-flat '("m6" "m7") output: "lib.o1.c")
+*** WARNING -- "*" is not defined,
+***            referenced in: ("m6.c")
+*** WARNING -- "+" is not defined,
+***            referenced in: ("m7.c")
+*** WARNING -- "n" is not defined,
+***            referenced in: ("m7.c")
+"/Users/feeley/gambit/doc/lib.o1.c"
+> ,q
+$ gcc -bundle -D___DYNAMIC m6.c m7.c lib.o1.c -o lib.o1
+$ gsc
+Gambit v4.6.1
+
+> (load "lib")
+*** WARNING -- Variable "n" used in module "m7" is undefined
+"/Users/feeley/gambit/doc/lib.o1"
+> (define n 10)
+> (f 5)
+35
+> ,q
+
+ +

The warnings indicate that there are no definitions (defines or +set!s) of the variables *, + and n in the +modules contained in the library. Before the library is used, these +variables will have to be bound; either implicitly (by the runtime +library) or explicitly. +

+ + +
+ + + + + + + + + + + +
Back: 3.5 Procedures specific to compilerForward: 5. Debugging   FastBack: 3. The Gambit Scheme compilerUp: Gambit-CFastForward: 5. DebuggingTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

4. Runtime options

+ + + + + +

Both gsi and gsc as well as executable programs compiled +and linked using gsc take a -: option which supplies +parameters to the runtime system. This option must appear first on +the command line. The colon is followed by a comma separated list of +options with no intervening spaces. The available options are: +

+
+
mHEAPSIZE
+

Set minimum heap size in kilobytes. +

+
hHEAPSIZE
+

Set maximum heap size in kilobytes. +

+
lLIVEPERCENT
+

Set heap occupation after garbage collection. +

+
s
+

Select standard Scheme mode. +

+
S
+

Select Gambit Scheme mode. +

+
d[OPT...]
+

Set debugging options. +

+
@[INTF][:PORT]
+

Override the configuration of the main RPC server. +

+
=DIRECTORY
+

Override the central installation directory. +

+
~~DIR=DIRECTORY
+

Override the DIR installation directory. +

+
+ARGUMENT
+

Add ARGUMENT to the command line before other arguments. +

+
f[OPT...]
+

Set file options. +

+
t[OPT...]
+

Set terminal options. +

+
-[OPT...]
+

Set standard input and output options. +

+
+ + +

The m option specifies the minimum size of the heap. The +m is immediately followed by an integer indicating the number +of kilobytes of memory. The heap will not shrink lower than this +size. By default, the minimum size is 0. +

+ +

The h option specifies the maximum size of the heap. The +h is immediately followed by an integer indicating the number +of kilobytes of memory. The heap will not grow larger than this size. +By default, there is no limit (i.e. the heap will grow until the +virtual memory is exhausted). +

+ +

The l option specifies the percentage of the heap that will be +occupied with live objects after the heap is resized at the end of a +garbage collection. The l is immediately followed by an +integer between 1 and 100 inclusively indicating the desired +percentage. The garbage collector resizes the heap to reach this +percentage occupation. By default, the percentage is 50. +

+ + +

The s option selects standard Scheme mode. In this mode the +reader is case-insensitive and keywords are not recognized. The +S option selects Gambit Scheme mode (the reader is case-sensitive +and recognizes keywords which end with a colon). By default Gambit +Scheme mode is used. +

+ +

The d option sets various debugging options. The letter +d is followed by a sequence of letters indicating suboptions. +

+
+
p
+
+

Uncaught exceptions will be treated as “errors” in the primordial thread +only. +

+
+
a
+
+

Uncaught exceptions will be treated as “errors” in all threads. +

+
+
r
+
+

When an “error” occurs a new REPL will be started. +

+
+
s
+
+

When an “error” occurs a new REPL will be started. +Moreover the program starts in single-stepping mode. +

+
+
q
+
+

When an “error” occurs the program will terminate with a nonzero +exit status. +

+
+
R
+
+ +

When a user interrupt occurs a new REPL will be started. User +interrupts are typically obtained by typing <^C>. Note that with +some system configurations <^C> abruptly terminates the process. +For example, under Microsoft Windows, <^C> works fine with the +standard console but with the MSYS terminal window it terminates the +process. +

+
+
D
+
+

When a user interrupt occurs it will be deferred until the parameter +current-user-interrupt-handler is bound. +

+
+
Q
+
+

When a user interrupt occurs the program will terminate with a nonzero +exit status. +

+
+
LEVEL
+
+

The verbosity level is set to LEVEL (a digit from 0 to 9). +At level 0 the runtime system will not display error messages +and warnings. +

+
+
i
+
+

The REPL interaction channel will be the IDE REPL window (if the IDE +is available). +

+
+
c
+
+

The REPL interaction channel will be the console. +

+
+
-
+
+

The REPL interaction channel will be standard input and standard output. +

+
+
@[HOST][:PORT]
+
+

The REPL interaction channel will be connected to the remote debugger +at address HOST:PORT (if there is a remote debugger at +that address). The default HOST is 127.0.0.1 and the default +PORT is 44555. +THIS OPTION IS NOT YET IMPLEMENTED! +

+
+
+ +

The default debugging options are equivalent to -:dpqQ1i +(i.e. an uncaught exception in the primordial thread terminates the +program after displaying an error message). When the letter d +is not followed by suboptions, it is equivalent to -:dprR1i +(i.e. a new REPL is started only when an uncaught exception occurs in +the primordial thread). When gsi and gsc are running +the main REPL, the debugging options are changed to cause errors in +the primordial thread and user interrupts to start a nested REPL. +

+ +

The @[INTF][:PORT] option +overrides the configuration of the main RPC server. The default +INTF is 127.0.0.1 and the default PORT is 44556. +THIS OPTION IS NOT YET IMPLEMENTED! +

+ +

The =DIRECTORY option overrides the setting of the +central installation directory. +

+ +

The ~~DIR=DIRECTORY option overrides the setting of +the DIR installation directory. +

+ +

The + option adds the text that follows to the command line +before other arguments. +

+ + + +

The f, t and - options specify the default +settings of the ports created for files, terminals and standard input +and output respectively. The default character encoding, end-of-line +encoding and buffering can be set. Moreover, for terminals the +line-editing feature can be enabled or disabled. The f, +t and - must be followed by a sequence of these options: +

+
+
A
+

ASCII character encoding. +

+
1
+

ISO-8859-1 character encoding. +

+
2
+

UCS-2 character encoding. +

+
4
+

UCS-4 character encoding. +

+
6
+

UTF-16 character encoding. +

+
8
+

UTF-8 character encoding. +

+
U
+

UTF character encoding with fallback to UTF-8 on input if no BOM is present. +

+
UA
+

UTF character encoding with fallback to ASCII on input if no BOM is present. +

+
U1
+

UTF character encoding with fallback to ISO-8859-1 on input if no BOM is present. +

+
U6
+

UTF character encoding with fallback to UTF-16 on input if no BOM is present. +

+
U8
+

UTF character encoding with fallback to UTF-8 on input if no BOM is present. +

+
c
+

End-of-line is encoded as CR (carriage-return). +

+
l
+

End-of-line is encoded as LF (linefeed) +

+
cl
+

End-of-line is encoded as CR-LF. +

+
u
+

Unbuffered I/O. +

+
n
+

Line buffered I/O (n for “at newline”). +

+
f
+

Fully buffered I/O. +

+
r
+

Illegal character encoding is treated as an error (exception raised). +

+
R
+

Silently replace illegal character encodings with Unicode character #xfffd +(replacement character). +

+
e
+

Enable line-editing (applies to terminals only). +

+
E
+

Disable line-editing (applies to terminals only). +

+
+ + + +

When a program’s execution starts, the runtime system obtains the +runtime options by processing in turn four sources of runtime options: +the defaults, the environment variable GAMBCOPT, the script +line of the source code, and the first command line argument of the +program. Any runtime option can be overriden by a subsequent source +of runtime options. It is sometimes useful to prevent overriding +the runtime options of the script line. This can be achieved by +starting the script line runtime options with -::. In +this case the environment variable GAMBCOPT is ignored, +and the first command line argument of the program is +not used for runtime options (it is treated like a normal +command line argument). +

+

For example: +

+
 
$ GAMBCOPT=d0,=~/my-gambit2
+$ export GAMBCOPT
+$ gsi -e '(pretty-print (path-expand "~~")) (/ 1 0)'
+"/Users/feeley/my-gambit2/"
+$ echo $?
+70
+$ gsi -:d1 -e '(pretty-print (path-expand "~~")) (/ 1 0)'
+"/Users/feeley/my-gambit2/"
+*** ERROR IN (string)@1.3 -- Divide by zero
+(/ 1 0)
+
+ +
+ + + + + + + + + + + +
Back: 4. Runtime optionsForward: 5.1 Debugging model   FastBack: 4. Runtime optionsUp: Gambit-CFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5. Debugging

+ + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 5. DebuggingForward: 5.2 Debugging commands   FastBack: 5. DebuggingUp: 5. DebuggingFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5.1 Debugging model

+ +

The evaluation of an expression may stop before it is completed for the +following reasons: +

+
    +
  1. An evaluation error has occured, such as attempting to +divide by zero. + + +
  2. The user has interrupted the evaluation (usually by typing <^C>). + +
  3. A breakpoint has been reached or (step) was evaluated. + +
  4. Single-stepping mode is enabled. + +
+ +

When an evaluation stops, a message is displayed indicating the reason +and location where the evaluation was stopped. The location +information includes, if known, the name of the procedure where the +evaluation was stopped and the source code location in the format +stream@line.column, where stream is +either a string naming a file or a symbol within parentheses, such as +(console). +

+

A nested REPL is then initiated in the context of the point of +execution where the evaluation was stopped. The nested REPL’s +continuation and evaluation environment are the same as the point where +the evaluation was stopped. For example when evaluating the expression +(let ((y (- 1 1))) (* (/ x y) 2)), a “divide by zero” error is +reported and the nested REPL’s continuation is the one that takes the +result and multiplies it by two. The REPL’s lexical environment +includes the lexical variable y. This allows the inspection of +the evaluation context (i.e. the lexical and dynamic environments and +continuation), which is particularly useful to determine the exact +location and cause of an error. +

+ +

The prompt of nested REPLs includes the nesting level; 1> is the +prompt at the first nesting level, 2> at the second nesting +level, and so on. An end of file (usually <^D>) will cause the +current REPL to be terminated and the enclosing REPL (one nesting level +less) to be resumed. +

+

At any time the user can examine the frames in the REPL’s +continuation, which is useful to determine which chain of procedure +calls lead to an error. A backtrace that lists the chain of active +continuation frames in the REPL’s continuation can be obtained with +the ,b command. The frames are numbered from 0, that is frame +0 is the most recent frame of the continuation where execution +stopped, frame 1 is the parent frame of frame 0, and so on. It is +also possible to move the REPL to a specific parent continuation +(i.e. a specific frame of the continuation where execution stopped) +with the ,N, ,N+, ,N-, +,+, ,-, ,++, and ,-- commands. When the +frame number of the frame being examined is not zero, it is shown in +the prompt after the nesting level, for example 1\5> is the +prompt when the REPL nesting level is 1 and the frame number is 5. +

+

Expressions entered at a nested REPL are evaluated in the environment +(both lexical and dynamic) of the continuation frame currently being +examined if that frame was created by interpreted Scheme code. If the +frame was created by compiled Scheme code then expressions get evaluated +in the global interaction environment. This feature may be used in +interpreted code to fetch the value of a variable in the current frame +or to change its value with set!. Note that some special forms +(define in particular) can only be evaluated in the global +interaction environment. +

+
+ + + + + + + + + + + +
Back: 5.1 Debugging modelForward: 5.3 Debugging example   FastBack: 5. DebuggingUp: 5. DebuggingFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5.2 Debugging commands

+ +

In addition to expressions, the REPL accepts the following special +“comma” commands: +

+
+
,?
+
+

Give a summary of the REPL commands. +

+
+
,(h subject)
+
+

This command will show the section of the Gambit manual with the +definition of the procedure or special form subject, which must +be a symbol. For example ,(h time) will show the section +documenting the time special form. Please see the help +procedure for additional information. +

+
+
,h
+
+

This command will show the section of the Gambit manual with the +definition of the procedure which raised the exception for which this +REPL was started. +

+
+
,q
+
+

Terminate the process with exit status 0. This is equivalent to +calling (exit 0). +

+
+
,qt
+
+

Terminate the current thread (note that terminating the primordial +thread terminates the process). +

+
+
,t
+
+

Return to the outermost REPL, also known as the “top-level REPL”. +

+
+
,d
+
+

Leave the current REPL and resume the enclosing REPL. This command does +nothing in the top-level REPL. +

+
+
,(c expr)
+
+

Leave the current REPL and continue the computation that initiated the +REPL with a specific value. This command can only be used to continue +a computation that signaled an error. The expression expr is +evaluated in the current context and the resulting value is returned +as the value of the expression which signaled the error. For example, +if the evaluation of the expression (* (/ x y) 2) signaled an +error because y is zero, then in the nested REPL a ,(c (+ +4 y)) will resume the computation of (* (/ x y) 2) as though +the value of (/ x y) was 4. This command must be used +carefully because the context where the error occured may rely on the +result being of a particular type. For instance a ,(c #f) in +the previous example will cause * to signal a type error (this +problem is the most troublesome when debugging Scheme code that was +compiled with type checking turned off so be careful). +

+
+
,c
+
+

Leave the current REPL and continue the computation that initiated the +REPL. This command can only be used to continue a computation that was +stopped due to a user interrupt, breakpoint or a single-step. +

+
+
,s
+
+

Leave the current REPL and continue the computation that initiated the +REPL in single-stepping mode. The computation will perform an +evaluation step (as defined by step-level-set!) and then stop, +causing a nested REPL to be entered. Just before the evaluation step is +performed, a line is displayed (in the same format as trace) +which indicates the expression that is being evaluated. If the +evaluation step produces a result, the result is also displayed on +another line. A nested REPL is then entered after displaying a message +which describes the next step of the computation. This command can +only be used to continue a computation that was stopped due to a user +interrupt, breakpoint or a single-step. +

+
+
,l
+
+

This command is similar to ,s except that it “leaps” over +procedure calls, that is procedure calls are treated like a single step. +Single-stepping mode will resume when the procedure call returns, or if +and when the execution of the called procedure encounters a breakpoint. +

+
+
,N
+
+

Move to frame number N of the continuation. After changing the +current frame, a one-line summary of the frame is displayed as if the +,y command was entered. +

+
+
,N+
+
+

Move forward by N frames in the chain of continuation frames +(i.e. towards older continuation frames). After changing the current +frame, a one-line summary of the frame is displayed as if the +,y command was entered. +

+
+
,N-
+
+

Move backward by N frames in the chain of continuation frames +(i.e. towards more recent continuation frames). After changing the +current frame, a one-line summary of the frame is displayed as if the +,y command was entered. +

+
+
,+
+
+

Equivalent to ,1+. +

+
+
,-
+
+

Equivalent to ,1-. +

+
+
,++
+
+

Equivalent to ,N+ where N is the number of +continuation frames displayed at the head of a backtrace. +

+
+
,--
+
+

Equivalent to ,N- where N is the number of +continuation frames displayed at the head of a backtrace. +

+
+
,y
+
+

Display a one-line summary of the current frame. The information is +displayed in four fields. The first field is the frame number. The +second field is the procedure that created the frame or +(interaction) if the frame was created by an expression entered +at the REPL. The remaining fields describe the subproblem associated +with the frame, that is the expression whose value is being computed. +The third field is the location of the subproblem’s source code and +the fourth field is a reproduction of the source code, possibly +truncated to fit on the line. The last two fields may be missing if +that information is not available. In particular, the third field is +missing when the frame was created by a user call to the eval +procedure or by a compiled procedure not compiled with the declaration +debug-location, and the last field is missing when the frame +was created by a compiled procedure not compiled with the declaration +debug-source. +

+
+
,b
+
+

Display a backtrace summarizing each frame in the chain of continuation +frames starting with the current frame. For each frame, the same +information as for the ,y command is displayed (except that +location information is displayed in the format +stream@line:column). If there are more than 15 +frames in the chain of continuation frames, some of the middle frames +will be omitted. +

+
+
,be
+
+

Like the ,b command but also display the environment. +

+
+
,bed
+
+

Like the ,be command but also display the dynamic environment. +

+
+
,(b expr)
+
+

Display the backtrace of expr’s value, X, which is +obtained by evaluating expr in the current frame. X must +be a continuation or a thread. When X is a continuation, the +frames in that continuation are displayed. When X is a thread, +the backtrace of the current continuation of that thread is displayed. +

+
+
,(be expr)
+
+

Like the ,(b expr) command but also display the +environment. +

+
+
,(bed expr)
+
+

Like the ,(be expr) command but also display the dynamic +environment. +

+
+
,i
+
+

Pretty print the procedure that created the current frame or +(interaction) if the frame was created by an expression entered +at the REPL. Compiled procedures will only be pretty printed when +they are compiled with the declaration debug-source. +

+
+
,e
+
+

Display the environment which is accessible from the current frame. +The lexical environment is displayed, followed by the dynamic +environment if the parameter object +repl-display-dynamic-environment? is not false. Global lexical +variables are not displayed. Moreover the frame must have been +created by interpreted code or code compiled with the declaration +debug-environments. Due to space safety +considerations and compiler optimizations, some of the lexical +variable bindings may be missing. Lexical variable bindings are +displayed using the format variable = expression +(when variable is mutable) or variable == expression +(when variable is immutable, which may happen in compiled code +due to compiler optimization) +and dynamically-bound parameter bindings are displayed using the +format (parameter) = expression. Note that +expression can be a self-evaluating expression (number, string, +boolean, character, ...), a quoted expression, a lambda expression or +a global variable (the last two cases, which are only used when the +value of the variable or parameter is a procedure, simplifies the +debugging of higher-order procedures). A parameter can be a +quoted expression or a global variable. Lexical bindings are +displayed in inverse binding order (most deeply nested first) and +shadowed variables are included in the list. +

+
+
,ed
+
+

Like the ,e command but the dynamic environment is always +displayed. +

+
+
,(e expr)
+
+

Display the environment of expr’s value, X, which is +obtained by evaluating expr in the current frame. X must +be a continuation, a thread, a procedure, or a nonnegative integer. +When X is a continuation, the environment at that point in the +code is displayed. When X is a thread, the environment of the +current continuation of that thread is displayed. When X is a +procedure, the lexical environment where X was created is +combined with the current continuation and this combined environment +is displayed. When X is an integer, the environment at frame +number X of the continuation is displayed. +

+
+
,(ed expr)
+
+

Like the ,(e expr) command but the dynamic environment is +always displayed. +

+
+
,st
+
+

Display the state of the threads in the current thread’s thread group. +A thread can be: uninitialized, initialized, active, and +terminated (normally or abnormally). Active threads can be +running, sleeping and waiting on a synchronization object +(mutex, condition variable or port) possibly with a timeout. +

+
+
,(st expr)
+
+

Display the state of a specific thread or thread group. +The value of expr must be a thread or thread group. +

+
+
,(v expr)
+
+

Start a new REPL visiting expr’s value, X, which is +obtained by evaluating expr in the current frame. X must +be a continuation, a thread, a procedure, or a nonnegative integer. +When X is a continuation, the new REPL’s continuation is X +and evaluations are done in the environment at that point in the code. +When X is a thread, the thread is interrupted and the new REPL’s +continuation is the point where the thread was interrupted. When +X is a procedure, the lexical environment where X was +created is combined with the current continuation and evaluations are +done in this combined environment. When X is an integer, the +REPL is started in frame number X of the continuation. +

+
+
+ +
+ + + + + + + + + + + +
Back: 5.2 Debugging commandsForward: 5.4 Procedures related to debugging   FastBack: 5. DebuggingUp: 5. DebuggingFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5.3 Debugging example

+ +

Here is a sample interaction with gsi: +

+
 
$ gsi
+Gambit v4.6.1
+
+> (define (invsqr x) (/ 1 (expt x 2)))
+> (define (mymap fn lst)
+    (define (mm in)
+      (if (null? in)
+          '()
+          (cons (fn (car in)) (mm (cdr in)))))
+    (mm lst))
+> (mymap invsqr '(5 2 hello 9 1))
+*** ERROR IN invsqr, (console)@1.25 -- (Argument 1) NUMBER expected
+(expt 'hello 2)
+1> ,i
+#<procedure #2 invsqr> =
+(lambda (x) (/ 1 (expt x 2)))
+1> ,e
+x = 'hello
+1> ,b
+0  invsqr                    (console)@1:25          (expt x 2)
+1  #<procedure #4>           (console)@6:17          (fn (car in))
+2  #<procedure #4>           (console)@6:31          (mm (cdr in))
+3  #<procedure #4>           (console)@6:31          (mm (cdr in))
+4  (interaction)             (console)@8:1           (mymap invsqr '(5 2 hel...
+1> ,+
+1  #<procedure #4>           (console)@6.17          (fn (car in))
+1\1> (pp #4)
+(lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
+1\1> ,e
+in = '(hello 9 1)
+mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
+fn = invsqr
+lst = '(5 2 hello 9 1)
+1\1> ,(e mm)
+mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
+fn = invsqr
+lst = '(5 2 hello 9 1)
+1\1> fn
+#<procedure #2 invsqr>
+1\1> (pp fn)
+(lambda (x) (/ 1 (expt x 2)))
+1\1> ,+
+2  #<procedure #4>           (console)@6.31          (mm (cdr in))
+1\2> ,e
+in = '(2 hello 9 1)
+mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
+fn = invsqr
+lst = '(5 2 hello 9 1)
+1\2> ,(c (list 3 4 5))
+(1/25 1/4 3 4 5)
+> ,q
+
+ +
+ + + + + + + + + + + +
Back: 5.3 Debugging exampleForward: 5.5 Console line-editing   FastBack: 5. DebuggingUp: 5. DebuggingFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5.4 Procedures related to debugging

+ +
(help subject)procedure
+
(help-browser [new-value])procedure
+ +

The help procedure displays the section of the Gambit manual +with the definition of the procedure or special form subject, +which must be a procedure or symbol. For example the call (help +gensym) will show the section documenting the gensym procedure +and the call (help 'time) will show the section documenting the +time special form. The help procedure returns the void +object. +

+

The parameter object help-browser is bound to a string naming +the external program that is used by the help procedure to view +the documentation. Initially it is bound to the empty string. In +normal circumstances when help-browser is bound to an empty +string the help procedure runs the script +~~bin/gambc-doc.bat which searches for a suitable web browser +to open the documentation in HTML format. Unless the system was built +with the command configure --enable-help-browser=..., the +text-only browser lynx (see http://lynx.isc.org/) will +be used by default if it is available. We highly recommend that you +install this browser if you are interested in viewing the +documentation within the console in which the REPL is running. You +can exit lynx conveniently by typing an end of file (usually +<^D>). +

+

For example: +

+
 
> (help-browser "firefox") ; use firefox instead of lynx
+> (help 'gensym)
+> (help gensym) ; OK because gensym is a procedure
+> (help 'time)
+> (help time) ; not OK because time is a special form
+*** ERROR IN (console)@5.7 -- Macro name can't be used as a variable: time
+> 
+
+ + + +
(repl-result-history-ref i)procedure
+
(repl-result-history-max-length-set! n)procedure
+ + + +

The REPL keeps a history of the last few results printed by the +REPL. The call (repl-result-history-ref i) returns the +ith previous result (the last for i=0, the next to last +for i=1, etc). By default the REPL result history remembers up +to 3 results. The maximal length of the history can be set to n +between 0 and 10 by a call to +(repl-result-history-max-length-set! n). +

+

For convenience the reader defines an abbreviation for calling +repl-result-history-ref. Tokens formed by a sequence of one or +more hash signs, such as #, ##, etc, are +expanded by the reader into the list (repl-result-history-ref +i), where i is the number of hash signs minus 1. In +other words, # will return the last result printed by +the REPL, ## will return the next to last, etc. +

+

For example: +

+
 
> (map (lambda (x) (* x x)) '(1 2 3))
+(1 4 9)
+> (reverse #)
+(9 4 1)
+> (append # ##)
+(9 4 1 1 4 9)
+> 1
+1
+> 1
+1
+> (+ # ##)
+2
+> (+ # ##)
+3
+> (+ # ##)
+5
+> ####
+*** ERROR IN (console)@9.1 -- (Argument 1) Out of range
+(repl-result-history-ref 3)
+1> 
+
+ + + +
(trace proc)procedure
+
(untrace proc)procedure
+ +

The trace procedure starts tracing calls to the specified +procedures. When a traced procedure is called, a line containing the +procedure and its arguments is displayed (using the procedure call +expression syntax). The line is indented with a sequence of vertical +bars which indicate the nesting depth of the procedure’s continuation. +After the vertical bars is a greater-than sign which indicates that +the evaluation of the call is starting. +

+

When a traced procedure returns a result, it is displayed with the same +indentation as the call but without the greater-than sign. This makes +it easy to match calls and results (the result of a given call is the +value at the same indentation as the greater-than sign). If a traced +procedure P1 performs a tail call to a traced procedure P2, then P2 will +use the same indentation as P1. This makes it easy to spot tail calls. +The special handling for tail calls is needed to preserve the space +complexity of the program (i.e. tail calls are implemented as required +by Scheme even when they involve traced procedures). +

+

The untrace procedure stops tracing calls to the specified +procedures. When no argument is passed to the trace +procedure, the list of procedures currently being traced is returned. +The void object is returned by the trace procedure when it is +passed one or more arguments. When no argument is passed to the +untrace procedure stops all tracing and returns the void +object. A compiled procedure may be traced but only if it is bound to +a global variable. +

+

For example: +

+
 
> (define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))
+> (trace fact)
+> (fact 5)
+| > (fact 5)
+| | > (fact 4)
+| | | > (fact 3)
+| | | | > (fact 2)
+| | | | | > (fact 1)
+| | | | | 1
+| | | | 2
+| | | 6
+| | 24
+| 120
+120
+> (trace -)
+*** WARNING -- Rebinding global variable "-" to an interpreted procedure
+> (define (fact-iter n r) (if (< n 2) r (fact-iter (- n 1) (* n r))))
+> (trace fact-iter)
+> (fact-iter 5 1)
+| > (fact-iter 5 1)
+| | > (- 5 1)
+| | 4
+| > (fact-iter 4 5)
+| | > (- 4 1)
+| | 3
+| > (fact-iter 3 20)
+| | > (- 3 1)
+| | 2
+| > (fact-iter 2 60)
+| | > (- 2 1)
+| | 1
+| > (fact-iter 1 120)
+| 120
+120
+> (trace)
+(#<procedure #2 fact-iter> #<procedure #3 -> #<procedure #4 fact>)
+> (untrace)
+> (fact 5)
+120
+
+ + + +
(step)procedure
+
(step-level-set! level)procedure
+ +

The step procedure enables single-stepping mode. After the call +to step the computation will stop just before the interpreter +executes the next evaluation step (as defined by +step-level-set!). A nested REPL is then started. Note that +because single-stepping is stopped by the REPL whenever the prompt is +displayed it is pointless to enter (step) by itself. On the +other hand entering (begin (step) expr) will evaluate +expr in single-stepping mode. +

+

The procedure step-level-set! sets the stepping level which +determines the granularity of the evaluation steps when single-stepping +is enabled. The stepping level level must be an exact integer in +the range 0 to 7. At a level of 0, the interpreter ignores +single-stepping mode. At higher levels the interpreter stops the +computation just before it performs the following operations, depending +on the stepping level: +

+
    +
  1. +procedure call + + +
  2. +delay special form and operations at lower levels + +
  3. +lambda special form and operations at lower levels + +
  4. +define special form and operations at lower levels + +
  5. +set! special form and operations at lower levels + +
  6. +variable reference and operations at lower levels + +
  7. +constant reference and operations at lower levels + +
+ +

The default stepping level is 7. +

+

For example: +

+
 
> (define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))
+> (step-level-set! 1)
+> (begin (step) (fact 5))
+*** STOPPED IN (console)@3.15
+1> ,s
+| > (fact 5)
+*** STOPPED IN fact, (console)@1.22
+1> ,s
+| | > (< n 2)
+| | #f
+*** STOPPED IN fact, (console)@1.43
+1> ,s
+| | > (- n 1)
+| | 4
+*** STOPPED IN fact, (console)@1.37
+1> ,s
+| | > (fact (- n 1))
+*** STOPPED IN fact, (console)@1.22
+1> ,s
+| | | > (< n 2)
+| | | #f
+*** STOPPED IN fact, (console)@1.43
+1> ,s
+| | | > (- n 1)
+| | | 3
+*** STOPPED IN fact, (console)@1.37
+1> ,l
+| | | > (fact (- n 1))
+*** STOPPED IN fact, (console)@1.22
+1> ,l
+| | > (* n (fact (- n 1)))
+| | 24
+*** STOPPED IN fact, (console)@1.32
+1> ,l
+| > (* n (fact (- n 1)))
+| 120
+120
+
+ + + +
(break proc)procedure
+
(unbreak proc)procedure
+ +

The break procedure places a breakpoint on each of the +specified procedures. When a procedure is called that has a +breakpoint, the interpreter will enable single-stepping mode (as if +step had been called). This typically causes the computation +to stop soon inside the procedure if the stepping level is high +enough. +

+

The unbreak procedure removes the breakpoints on the specified +procedures. With no argument, break returns the list of +procedures currently containing breakpoints. The void object is +returned by break if it is passed one or more arguments. With +no argument unbreak removes all the breakpoints and returns the +void object. A breakpoint can be placed on a compiled procedure but +only if it is bound to a global variable. +

+

For example: +

+
 
> (define (double x) (+ x x))
+> (define (triple y) (- (double (double y)) y))
+> (define (f z) (* (triple z) 10))
+> (break double)
+> (break -)
+*** WARNING -- Rebinding global variable "-" to an interpreted procedure
+> (f 5)
+*** STOPPED IN double, (console)@1.21
+1> ,b
+0  double                    (console)@1:21          +
+1  triple                    (console)@2:31          (double y)
+2  f                         (console)@3:18          (triple z)
+3  (interaction)             (console)@6:1           (f 5)
+1> ,e
+x = 5
+1> ,c
+*** STOPPED IN double, (console)@1.21
+1> ,c
+*** STOPPED IN f, (console)@3.29
+1> ,c
+150
+> (break)
+(#<procedure #3 -> #<procedure #4 double>)
+> (unbreak)
+> (f 5)
+150
+
+ + + +
(generate-proper-tail-calls [new-value])procedure
+ + + + +

[Note: this procedure is DEPRECATED and will be removed +in a future version of Gambit. Use the proper-tail-calls +declaration instead.] +

+

The parameter object generate-proper-tail-calls is bound to a +boolean value controlling how the interpreter handles tail calls. +When it is bound to #f the interpreter will treat tail calls +like nontail calls, that is a new continuation will be created for the +call. This setting is useful for debugging, because when a primitive +signals an error the location information will point to the call site +of the primitive even if this primitive was called with a tail call. +The initial value of this parameter object is #t, which means +that a tail call will reuse the continuation of the calling function. +

+

This parameter object only affects code that is subsequently processed +by load or eval, or entered at the REPL. +

+

For example: +

+
 
> (generate-proper-tail-calls)
+#t
+> (let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))
+*** ERROR IN #<procedure #2>, (console)@2.47 -- Unbound variable: oops
+1> ,b
+0  #<procedure #2>           (console)@2:47          oops
+1  (interaction)             (console)@2:1           ((letrec ((loop (lambda...
+1> ,t
+> (generate-proper-tail-calls #f)
+> (let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))
+*** ERROR IN #<procedure #3>, (console)@6.47 -- Unbound variable: oops
+1> ,b
+0  #<procedure #3>           (console)@6:47          oops
+1  #<procedure #3>           (console)@6:32          (loop (* i 2))
+2  #<procedure #3>           (console)@6:32          (loop (* i 2))
+3  #<procedure #3>           (console)@6:32          (loop (* i 2))
+4  #<procedure #3>           (console)@6:32          (loop (* i 2))
+5  (interaction)             (console)@6:1           ((letrec ((loop (lambda...
+
+
+ + + +
(display-environment-set! display?)procedure
+ +

[Note: this procedure is DEPRECATED and will be removed +in a future version of Gambit. Use the parameter object +repl-display-environment? instead.] +

+

This procedure sets a flag that controls the automatic display of the +environment by the REPL. If display? is true, the environment +is displayed by the REPL before the prompt. The default setting is +not to display the environment. +

+ + +
(repl-display-environment? display?)procedure
+ +

The parameter object repl-display-environment? is bound to a +boolean value that controls the automatic display of the environment +by the REPL. If display? is true, the environment is displayed +by the REPL before the prompt. This is particularly useful in +single-stepping mode. The default setting is not to display the +environment. +

+ + +
(display-dynamic-environment? display?)procedure
+ +

The parameter object display-dynamic-environment? is bound to a +boolean value that controls wether the dynamic environment is +displayed when the environment is displayed. The default setting is +not to display the dynamic environment. +

+ + +
(pretty-print obj [port])procedure
+ +

This procedure pretty-prints obj on the port port. If it +is not specified, port defaults to the current output-port. +

+

For example: +

+
 
> (pretty-print
+    (let* ((x '(1 2 3 4)) (y (list x x x))) (list y y y)))
+(((1 2 3 4) (1 2 3 4) (1 2 3 4))
+ ((1 2 3 4) (1 2 3 4) (1 2 3 4))
+ ((1 2 3 4) (1 2 3 4) (1 2 3 4)))
+
+ + + +
(pp obj [port])procedure
+ +

This procedure pretty-prints obj on the port port. When +obj is a procedure created by the interpreter or a procedure +created by code compiled with the declaration +debug-source, the procedure’s source code is +displayed. If it is not specified, port defaults to the +interaction channel (i.e. the output will appear at the REPL). +

+

For example: +

+
 
> (define (f g) (+ (time (g 100)) (time (g 1000))))
+> (pp f)
+(lambda (g)
+  (+ (##time (lambda () (g 100)) '(g 100))
+     (##time (lambda () (g 1000)) '(g 1000))))
+
+ + + +
(gc-report-set! report?)procedure
+ + +

This procedure controls the generation of reports during garbage +collections. If the argument is true, a brief report of memory usage +is generated after every garbage collection. It contains: the time +taken for this garbage collection, the amount of memory allocated in +megabytes since the program was started, the size of the heap in +megabytes, the heap memory in megabytes occupied by live data, the +proportion of the heap occupied by live data, and the number of bytes +occupied by movable and nonmovable objects. +

+ + +
+ + + + + + + + + + + +
Back: 5.4 Procedures related to debuggingForward: 5.6 Emacs interface   FastBack: 5. DebuggingUp: 5. DebuggingFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5.5 Console line-editing

+ +

The console implements a simple Scheme-friendly line-editing +user-interface that is enabled by default. It offers parentheses +balancing, a history of previous commands, symbol completion, and +several emacs-compatible keyboard commands. The user’s input is +displayed in a bold font and the output produced by the system is in a +plain font. The history of previous commands is saved in the file +‘~/.gambc_history’. It is restored when a REPL is started. +

+

Symbol completion is triggered with the tab key. When the cursor is +after a sequence of characters that can form a symbol, typing the tab +key will search the symbol table for the first symbol (in alphabetical +order) that begins with that sequence and insert that symbol. Typing +the tab key in succession will cycle through all symbols with that +prefix. When all possible symbols have been shown or there are no +possible completions, the text reverts to the uncompleted symbol and +the bell is rung. +

+

Here are the keyboard commands available (where the M- +prefix means the escape key is typed and the C- prefix +means the control key is pressed): +

+
+
C-d
+

Generate an end-of-file when the line is empty, otherwise delete +character at cursor. +

+
+
delete or backspace
+

Delete character before cursor. +

+
+
M-C-d
+

Delete word forward and keep a copy of this text on the clipboard. +

+
+
M-delete
+

Delete word backward and keep a copy of this text on the clipboard. +

+
+
M-backspace
+

Delete S-expression backward and keep a copy of this text on the clipboard. +

+
+
C-a
+

Move cursor to beginning of line. +

+
+
C-e
+

Move cursor to end of line. +

+
+
C-b or left-arrow
+

Move cursor left one character. +

+
+
M-b
+

Move cursor left one word. +

+
+
M-C-b or M-left-arrow
+

Move cursor left one S-expression. +

+
+
C-f or right-arrow
+

Move cursor right one character. +

+
+
M-f
+

Move cursor right one word. +

+
+
M-C-f or M-right-arrow
+

Move cursor right one S-expression. +

+
+
C-p or M-p or up-arrow
+

Move to previous line in history. +

+
+
C-n or M-n or down-arrow
+

Move to next line in history. +

+
+
C-t
+

Transpose character at cursor with previous character. +

+
+
M-t
+

Transpose word after cursor with previous word. +

+
+
M-C-t
+

Transpose S-expression after cursor with previous S-expression. +

+
+
C-l
+

Clear console and redraw line being edited. +

+
+
C-nul
+

Set the mark to the cursor. +

+
+
C-w
+

Delete the text between the cursor and the mark and keep a copy +of this text on the clipboard. +

+
+
C-k
+

Delete the text from the cursor to the end of the line and keep a copy +of this text on the clipboard. +

+
+
C-y
+

Paste the text that is on the clipboard. +

+
+
F8
+

Same as typing #||#,c; (REPL command to continue the computation). +

+
+
F9
+

Same as typing #||#,-; (REPL command to move to newer frame). +

+
+
F10
+

Same as typing #||#,+; (REPL command to move to older frame). +

+
+
F11
+

Same as typing #||#,s; (REPL command to step the computation). +

+
+
F12
+

Same as typing #||#,l; (REPL command to leap the computation). +

+
+
+ +

On Mac OS X, depending on your configuration, you may have to press +the fn key to access the function key F12 and the +option key to access the other function keys. +

+

On Microsoft Windows the clipboard is the system clipboard. This +allows text to be copied and pasted between the program and other +applications. On other operating systems the clipboard is internal to +the program (it is not integrated with the operating system). +

+
+ + + + + + + + + + + +
Back: 5.5 Console line-editingForward: 5.7 GUIDE   FastBack: 5. DebuggingUp: 5. DebuggingFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5.6 Emacs interface

+ + + +

Gambit comes with the Emacs package gambit.el which provides a +nice environment for running Gambit from within the Emacs editor. +This package filters the standard output of the Gambit process and +when it intercepts a location information (in the format +stream@line.column where stream is +either (stdin) when the expression was obtained from standard +input, (console) when the expression was obtained from the +console, or a string naming a file) it opens a window to highlight the +corresponding expression. +

+

To use this package, make sure the file gambit.el is accessible +from your load-path and that the following lines are in your +.emacs file: +

+
 
(autoload 'gambit-inferior-mode "gambit" "Hook Gambit mode into cmuscheme.")
+(autoload 'gambit-mode "gambit" "Hook Gambit mode into scheme.")
+(add-hook 'inferior-scheme-mode-hook (function gambit-inferior-mode))
+(add-hook 'scheme-mode-hook (function gambit-mode))
+(setq scheme-program-name "gsi -:d-")
+
+ +

Alternatively, if you don’t mind always loading this package, +you can simply add this line to your .emacs file: +

+
 
(require 'gambit)
+
+ +

You can then start an inferior Gambit process by typing M-x +run-scheme. The commands provided in cmuscheme mode will be +available in the Gambit interaction buffer (i.e. *scheme*) and in +buffers attached to Scheme source files. Here is a list of the most +useful commands (for a complete list type C-h m in the Gambit +interaction buffer): +

+
C-x C-e
+

Evaluate the expression which is before the cursor (the expression will +be copied to the Gambit interaction buffer). +

+
C-c C-z
+

Switch to Gambit interaction buffer. +

+
C-c C-l
+

Load a file (file attached to current buffer is default) using +(load file). +

+
C-c C-k
+

Compile a file (file attached to current buffer is default) using +(compile-file file). +

+
+ +

The file gambit.el provides these additional commands: +

+
+
F8 or C-c c
+

Continue the computation (same as typing #||#,c; to the REPL). +

+
F9 or C-c ]
+

Move to newer frame (same as typing #||#,-; to the REPL). +

+
F10 or C-c [
+

Move to older frame (same as typing #||#,+; to the REPL). +

+
F11 or C-c s
+

Step the computation (same as typing #||#,s; to the REPL). +

+
F12 or C-c l
+

Leap the computation (same as typing #||#,l; to the REPL). +

+
C-c _
+

Removes the last window that was opened to highlight an expression. +

+
+ +

The two keystroke version of these commands can be shortened to +M-c, M-[, M-], M-s, M-l, and +M-_ respectively by adding this line to your .emacs +file: +

+
 
(setq gambit-repl-command-prefix "\e")
+
+ +

This is more convenient to type than the two keystroke C-c based +sequences but the purist may not like this because it does not follow +normal Emacs conventions. +

+

Here is what a typical .emacs file will look like: +

+
 
(setq load-path ; add directory containing gambit.el
+  (cons "/usr/local/Gambit-C/share/emacs/site-lisp"
+        load-path))
+(setq scheme-program-name "/tmp/gsi -:d-") ; if gsi not in executable path
+(setq gambit-highlight-color "gray") ; if you don't like the default
+(setq gambit-repl-command-prefix "\e") ; if you want M-c, M-s, etc
+(require 'gambit)
+
+ +
+ + + + + + + + + + + +
Back: 5.6 Emacs interfaceForward: 6. Scheme extensions   FastBack: 5. DebuggingUp: 5. DebuggingFastForward: 6. Scheme extensionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

5.7 GUIDE

+ +

The implementation and documentation for GUIDE, the Gambit Universal +IDE, are not yet complete. +

+
+ + + + + + + + + + + +
Back: 5.7 GUIDEForward: 6.1 Extensions to standard procedures   FastBack: 5. DebuggingUp: Gambit-CFastForward: 7. NamespacesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

6. Scheme extensions

+ + + + + + + + +
+ + + + + + + + + + + +
Back: 6. Scheme extensionsForward: 6.2 Extensions to standard special forms   FastBack: 6. Scheme extensionsUp: 6. Scheme extensionsFastForward: 7. NamespacesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

6.1 Extensions to standard procedures

+ +
(transcript-on file)procedure
+
(transcript-off)procedure
+ +

These procedures do nothing. +

+ + +
(call-with-current-continuation proc)procedure
+
(call/cc proc)procedure
+ +

The procedure call-with-current-continuation is bound to the +global variables call-with-current-continuation and +call/cc. +

+ + +
+ + + + + + + + + + + +
Back: 6.1 Extensions to standard proceduresForward: 6.3 Miscellaneous extensions   FastBack: 6. Scheme extensionsUp: 6. Scheme extensionsFastForward: 7. NamespacesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

6.2 Extensions to standard special forms

+ +
(lambda lambda-formals body)special form
+
(define (variable define-formals) body)special form
+ + + +

These forms are extended versions of the lambda and define +special forms of standard Scheme. They allow the use of optional formal +arguments, either positional or named, and support the syntax and semantics +of the DSSSL standard. +

+

When the procedure introduced by a lambda (or define) is +applied to a list of actual arguments, the formal and actual arguments +are processed as specified in the R4RS if the lambda-formals (or +define-formals) is a r4rs-lambda-formals (or +r4rs-define-formals). +

+

If the formal-argument-list matches +dsssl-formal-argument-list or extended-formal-argument-list +they are processed as follows: +

+
    +
  1. +Variables in required-formal-arguments are bound to +successive actual arguments starting with the first actual argument. It +shall be an error if there are fewer actual arguments than +required-formal-arguments. + +
  2. +Next variables in optional-formal-arguments are bound to +remaining actual arguments. If there are fewer remaining actual +arguments than optional-formal-arguments, then the variables are +bound to the result of evaluating initializer, if one was +specified, and otherwise to #f. The initializer is +evaluated in an environment in which all previous formal arguments have +been bound. + +
  3. +If #!key does not appear in the formal-argument-list +and there is no rest-formal-argument then it shall be an error +if there are any remaining actual arguments. + +
  4. +If #!key does not appear in the formal-argument-list +and there is a rest-formal-argument then the +rest-formal-argument is bound to a list of all remaining actual +arguments. + +
  5. +If #!key appears in the formal-argument-list and there is +no rest-formal-argument then there shall be an even number of +remaining actual arguments. These are interpreted as a series of +pairs, where the first member of each pair is a keyword specifying the +argument name, and the second is the corresponding value. It shall be +an error if the first member of a pair is not a keyword. It shall be +an error if the argument name is not the same as a variable in a +keyword-formal-argument. If the same argument name occurs more +than once in the list of actual arguments, then the first value is +used. If there is no actual argument for a particular +keyword-formal-argument, then the variable is bound to the +result of evaluating initializer if one was specified, and +otherwise to #f. The initializer is evaluated in an +environment in which all previous formal arguments have been bound. + +
  6. +If #!key appears in the formal-argument-list and there is +a rest-formal-argument before the #!key then there +may be an even or odd number of remaining actual arguments and the +rest-formal-argument is bound to a list of all remaining actual +arguments. Then, these remaining actual arguments are scanned from +left to right in pairs, stopping at the first pair whose first element +is not a keyword. Each pair whose first element is a keyword matching +the name of a keyword-formal-argument gives the value (i.e. the +second element of the pair) of the corresponding formal argument. If +the same argument name occurs more than once in the list of actual +arguments, then the first value is used. If there is no actual +argument for a particular keyword-formal-argument, then the +variable is bound to the result of evaluating initializer if one +was specified, and otherwise to #f. The initializer is +evaluated in an environment in which all previous formal arguments +have been bound. + +
  7. +If #!key appears in the formal-argument-list and there is +a rest-formal-argument after the #!key then there may +be an even or odd number of remaining actual arguments. The remaining +actual arguments are scanned from left to right in pairs, stopping at +the first pair whose first element is not a keyword. Each pair shall +have as its first element a keyword matching the name of a +keyword-formal-argument; the second element gives the value of +the corresponding formal argument. If the same argument name occurs +more than once in the list of actual arguments, then the first value +is used. If there is no actual argument for a particular +keyword-formal-argument, then the variable is bound to the +result of evaluating initializer if one was specified, and +otherwise to #f. The initializer is evaluated in an +environment in which all previous formal arguments have been bound. +Finally, the rest-formal-argument is bound to the list of the +actual arguments that were not scanned (i.e. after the last +keyword/value pair). +
+ +

In all cases it is an error for a variable to appear more than +once in a formal-argument-list. +

+

Note that this specification is compatible with the DSSSL language +standard (i.e. a correct DSSSL program will have the same semantics +when run with Gambit). +

+

It is unspecified whether variables receive their value by binding or by +assignment. Currently the compiler and interpreter use different +methods, which can lead to different semantics if +call-with-current-continuation is used in an initializer. +Note that this is irrelevant for DSSSL programs because +call-with-current-continuation does not exist in DSSSL. +

+

For example: +

+
 
> ((lambda (#!rest x) x) 1 2 3)
+(1 2 3)
+> (define (f a #!optional b) (list a b))
+> (define (g a #!optional (b a) #!key (k (* a b))) (list a b k))
+> (define (h1 a #!rest r #!key k) (list a k r))
+> (define (h2 a #!key k #!rest r) (list a k r))
+> (f 1)
+(1 #f)
+> (f 1 2)
+(1 2)
+> (g 3)
+(3 3 9)
+> (g 3 4)
+(3 4 12)
+> (g 3 4 k: 5)
+(3 4 5)
+> (g 3 4 k: 5 k: 6)
+(3 4 5)
+> (h1 7)
+(7 #f ())
+> (h1 7 k: 8 9)
+(7 8 (k: 8 9))
+> (h1 7 k: 8 z: 9)
+(7 8 (k: 8 z: 9))
+> (h2 7)
+(7 #f ())
+> (h2 7 k: 8 9)
+(7 8 (9))
+> (h2 7 k: 8 z: 9)
+*** ERROR IN (console)@17.1 -- Unknown keyword argument passed to procedure
+(h2 7 k: 8 z: 9)
+
+ + + +
+ + + + + + + + + + + +
Back: 6.2 Extensions to standard special formsForward: 6.4 Undocumented extensions   FastBack: 6. Scheme extensionsUp: 6. Scheme extensionsFastForward: 7. NamespacesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

6.3 Miscellaneous extensions

+ +
(vector-copy vector)procedure
+ +

This procedure returns a newly allocated vector with the same content +as the vector vector. Note that the elements are not +recursively copied. +

+

For example: +

+
 
> (define v1 '#(1 2 3))
+> (define v2 (vector-copy v1))
+> v2
+#(1 2 3)
+> (eq? v1 v2)
+#f
+
+ + + +
(subvector vector start end)procedure
+ +

This procedure is the vector analog of the substring +procedure. It returns a newly allocated vector formed from the +elements of the vector vector beginning with index start +(inclusive) and ending with index end (exclusive). +

+

For example: +

+
 
> (subvector '#(a b c d e f) 3 5)
+#(d e)
+
+ + + +
(vector-append vector)procedure
+ +

This procedure is the vector analog of the string-append +procedure. It returns a newly allocated vector whose elements +form the concatenation of the given vectors. +

+

For example: +

+
 
> (define v '#(1 2 3))
+> (vector-append v v v)
+#(1 2 3 1 2 3 1 2 3)
+
+ + + +
(append-vectors lst)procedure
+ +

This procedure returns a newly allocated vector whose elements form +the concatenation of all the vectors in the list lst. It is +equivalent to (apply vector-append lst). +

+

For example: +

+
 
> (define v '#(1 2 3))
+> (append-vectors (list v v v))
+#(1 2 3 1 2 3 1 2 3)
+
+ + + +
(subvector-fill! vector start end fill)procedure
+ +

This procedure is like vector-fill!, but fills a selected part +of the given vector. It sets the elements of the vector vector, +beginning with index start (inclusive) and ending with index +end (exclusive) to fill. The value returned is +unspecified. +

+

For example: +

+
 
> (define v (vector 'a 'b 'c 'd 'e 'f))
+> (subvector-fill! v 3 5 'x)
+> v
+#(a b c x x f)
+
+ + + +
(subvector-move! src-vector src-start src-end dst-vector dst-start)procedure
+ +

This procedure replaces part of the contents of vector +dst-vector with part of the contents of vector +src-vector. It copies elements from src-vector, beginning +with index src-start (inclusive) and ending with index +src-end (exclusive) to dst-vector beginning with index +dst-start (inclusive). The value returned is unspecified. +

+

For example: +

+
 
> (define v1 '#(1 2 3 4 5 6))
+> (define v2 (vector 'a 'b 'c 'd 'e 'f))
+> (subvector-move! v1 3 5 v2 1)
+> v2
+#(a 4 5 d e f)
+
+ + + +
(vector-shrink! vector k)procedure
+ +

This procedure shortens the vector vector so that its new size +is k. The value returned is unspecified. +

+

For example: +

+
 
> (define v (vector 'a 'b 'c 'd 'e 'f))
+> v
+#(a b c d e f)
+> (vector-shrink! v 3)
+> v
+#(a b c)
+
+ + + +
(append-strings lst)procedure
+ +

This procedure returns a newly allocated string whose elements form +the concatenation of all the strings in the list lst. It is +equivalent to (apply string-append lst). +

+

For example: +

+
 
> (define s "abc")
+> (append-strings (list s s s))
+"abcabcabc"
+
+ + + +
(substring-fill! string start end fill)procedure
+ +

This procedure is like string-fill!, but fills a selected part +of the given string. It sets the elements of the string string, +beginning with index start (inclusive) and ending with index +end (exclusive) to fill. The value returned is +unspecified. +

+

For example: +

+
 
> (define s (string #\a #\b #\c #\d #\e #\f))
+> (substring-fill! s 3 5 #\x)
+> s
+"abcxxf"
+
+ + + +
(substring-move! src-string src-start src-end dst-string dst-start)procedure
+ +

This procedure replaces part of the contents of string +dst-string with part of the contents of string +src-string. It copies elements from src-string, beginning +with index src-start (inclusive) and ending with index +src-end (exclusive) to dst-string beginning with index +dst-start (inclusive). The value returned is unspecified. +

+

For example: +

+
 
> (define s1 "123456")
+> (define s2 (string #\a #\b #\c #\d #\e #\f))
+> (substring-move! s1 3 5 s2 1)
+> s2
+"a45def"
+
+ + + +
(string-shrink! string k)procedure
+ +

This procedure shortens the string string so that its new size +is k. The value returned is unspecified. +

+

For example: +

+
 
> (define s (string #\a #\b #\c #\d #\e #\f))
+> s
+"abcdef"
+> (string-shrink! s 3)
+> s
+"abc"
+
+ + + +
(box obj)procedure
+
(box? obj)procedure
+
(unbox box)procedure
+
(set-box! box obj)procedure
+ + +

These procedures implement the box data type. A box is a +cell containing a single mutable field. The lexical syntax +of a box containing the object obj is #&obj +(see section Box syntax). +

+

The procedure box returns a new box object whose content is +initialized to obj. The procedure box? returns #t +if obj is a box, and otherwise returns #f. The procedure +unbox returns the content of the box box. The procedure +set-box! changes the content of the box box to obj. +The procedure set-box! returns an unspecified value. +

+

For example: +

+
 
> (define b (box 0))
+> b
+#&0
+> (define (inc!) (set-box! b (+ (unbox b) 1)))
+> (inc!)
+> b
+#&1
+> (unbox b)
+1
+
+ + + +
(keyword? obj)procedure
+
(keyword->string keyword)procedure
+
(string->keyword string)procedure
+ + +

These procedures implement the keyword data type. Keywords are +similar to symbols but are self evaluating and distinct from the +symbol data type. The lexical syntax of keywords is specified in +Keyword syntax. +

+

The procedure keyword? returns #t if obj is a +keyword, and otherwise returns #f. The procedure +keyword->string returns the name of keyword as a string. +The procedure string->keyword returns the keyword whose name is +string. +

+

For example: +

+
 
> (keyword? 'color)
+#f
+> (keyword? color:)
+#t
+> (keyword->string color:)
+"color"
+> (string->keyword "color")
+color:
+
+ + + +
(gensym [prefix])procedure
+ +

This procedure returns a new uninterned symbol. Uninterned symbols +are guaranteed to be distinct from the symbols generated by the +procedures read and string->symbol. The symbol +prefix is the prefix used to generate the new symbol’s name. If +it is not specified, the prefix defaults to g. +

+

For example: +

+
 
> (gensym)
+#:g0
+> (gensym)
+#:g1
+> (gensym 'star-trek-)
+#:star-trek-2
+
+ + + +
(make-uninterned-symbol name [hash])procedure
+
(uninterned-symbol? obj)procedure
+ +

The procedure make-uninterned-symbol returns a new uninterned +symbol whose name is name and hash is hash. The name must +be a string and the hash must be a nonnegative fixnum. +

+

The procedure uninterned-symbol? returns #t when +obj is a symbol that is uninterned and #f otherwise. +

+

For example: +

+
 
> (uninterned-symbol? (gensym))
+#t
+> (make-uninterned-symbol "foo")
+#:foo:
+> (uninterned-symbol? (make-uninterned-symbol "foo"))
+#t
+> (uninterned-symbol? 'hello)
+#f
+> (uninterned-symbol? 123)
+#f
+
+ + + +
(make-uninterned-keyword name [hash])procedure
+
(uninterned-keyword? obj)procedure
+ +

The procedure make-uninterned-keyword returns a new uninterned +keyword whose name is name and hash is hash. The name must +be a string and the hash must be a nonnegative fixnum. +

+

The procedure uninterned-keyword? returns #t when +obj is a keyword that is uninterned and #f otherwise. +

+

For example: +

+
 
> (make-uninterned-keyword "foo")
+#:foo:
+> (uninterned-keyword? (make-uninterned-keyword "foo"))
+#t
+> (uninterned-keyword? hello:)
+#f
+> (uninterned-keyword? 123)
+#f
+
+ + + +
(void)procedure
+ +

This procedure returns the void object. The read-eval-print loop +prints nothing when the result is the void object. +

+ + +
(eval expr [env])procedure
+ +

The first parameter is a datum representing an expression. The +eval procedure evaluates this expression in the global +interaction environment and returns the result. If present, the +second parameter is ignored (it is provided for compatibility with +R5RS). +

+

For example: +

+
 
> (eval '(+ 1 2))
+3
+> ((eval 'car) '(1 2))
+1
+> (eval '(define x 5))
+> x
+5
+
+ + + +
(include file)special form
+ +

The file parameter must be a string naming an existing file +containing Scheme source code. The include special form +splices the content of the specified source file. This form can only +appear where a define form is acceptable. +

+

For example: +

+
 
(include "macros.scm")
+
+(define (f lst)
+  (include "sort.scm")
+  (map sqrt (sort lst)))
+
+ + + +
(define-macro (name define-formals) body)special form
+ + +

Define name as a macro special form which expands into body. +This form can only appear where a define form is acceptable. +Macros are lexically scoped. The scope of a local macro definition +extends from the definition to the end of the body of the surrounding +binding construct. Macros defined at the top level of a Scheme module +are only visible in that module. To have access to the macro +definitions contained in a file, that file must be included using the +include special form. Macros which are visible from the REPL are +also visible during the compilation of Scheme source files. +

+

For example: +

+
 
(define-macro (unless test . body)
+  `(if ,test #f (begin ,@body)))
+
+(define-macro (push var #!optional val)
+  `(set! ,var (cons ,val ,var)))
+
+ +

To examine the code into which a macro expands you can use the +compiler’s -expansion option or the pp procedure. +For example: +

+
 
> (define-macro (push var #!optional val)
+    `(set! ,var (cons ,val ,var)))
+> (pp (lambda () (push stack 1) (push stack) (push stack 3)))
+(lambda ()
+  (set! stack (cons 1 stack))
+  (set! stack (cons #f stack))
+  (set! stack (cons 3 stack)))
+
+ + + +
(define-syntax name expander)special form
+ + + + + +

Define name as a macro special form whose expansion is specified +by expander. This form is available only when the runtime option +-:s is used. This option causes the loading of the +~~lib/syntax-case support library, which is the Hieb and Dybvig +portable syntax-case implementation which has been ported to +the Gambit interpreter and compiler. Note that this implementation of +syntax-case does not support special forms that are specific to +Gambit. +

+

For example: +

+
 
$ gsi -:s
+Gambit v4.6.1
+
+> (define-syntax unless
+    (syntax-rules ()
+      ((unless test body ...)
+       (if test #f (begin body ...)))))
+> (let ((test 111)) (unless (= 1 2) (list test test)))
+(111 111)
+> (pp (lambda () (let ((test 111)) (unless (= 1 2) (list test test)))))
+(lambda () ((lambda (%%test14) (if (= 1 2) #f (list %%test14 %%test14))) 111))
+> (unless #f (pp xxx))
+*** ERROR IN (console)@7.16 -- Unbound variable: xxx
+
+ + + +
(declare declaration)special form
+ +

This form introduces declarations to be used by the compiler +(currently the interpreter ignores the declarations). This form can +only appear where a define form is acceptable. Declarations +are lexically scoped in the same way as macros. The following +declarations are accepted by the compiler: +

+
+
(dialect)
+
+ + + +

Use the given dialect’s semantics. dialect can be: +ieee-scheme, r4rs-scheme, r5rs-scheme +or gambit-scheme. +

+
+
(strategy)
+
+ +

Select block compilation or separate compilation. In block +compilation, the compiler assumes that global variables defined in the +current file that are not mutated in the file will never be mutated. +strategy can be: block or separate. +

+
+
([not] inline)
+
+

Allow (or disallow) inlining of user procedures. +

+
+
([not] inline-primitives primitive…)
+
+

The given primitives should (or should not) be inlined +if possible (all primitives if none specified). +

+
+
(inlining-limit n)
+
+

Select the degree to which the compiler inlines user procedures. +n is the upper-bound, in percent, on code expansion that will +result from inlining. Thus, a value of 300 indicates that the size of +the program will not grow by more than 300 percent (i.e. it will be at +most 4 times the size of the original). A value of 0 disables inlining. +The size of a program is the total number of subexpressions it contains +(i.e. the size of an expression is one plus the size of its immediate +subexpressions). The following conditions must hold for a procedure to +be inlined: inlining the procedure must not cause the size of the call +site to grow more than specified by the inlining limit, the site of +definition (the define or lambda) and the call site must +be declared as (inline), and the compiler must be able to find +the definition of the procedure referred to at the call site (if the +procedure is bound to a global variable, the definition site must have a +(block) declaration). Note that inlining usually causes much +less code expansion than specified by the inlining limit (an expansion +around 10% is common for n=350). +

+
+
([not] lambda-lift)
+
+

Lambda-lift (or don’t lambda-lift) locally defined procedures. +

+
+
([not] constant-fold)
+
+

Allow (or disallow) constant-folding of primitive procedures. +

+
+
([not] standard-bindings var…)
+
+

The given global variables are known (or not known) to be equal to +the value defined for them in the dialect (all variables defined in +the standard if none specified). +

+
+
([not] extended-bindings var…)
+
+

The given global variables are known (or not known) to be equal to the +value defined for them in the runtime system (all variables defined +in the runtime if none specified). +

+
+
([not] run-time-bindings var…)
+
+

The given global variables will be tested at run time to see if they +are equal to the value defined for them in the runtime system (all +variables defined in the runtime if none specified). +

+
+
([not] safe)
+
+

Generate (or don’t generate) code that will prevent fatal errors at +run time. Note that in safe mode certain semantic errors will +not be checked as long as they can’t crash the system. For example +the primitive char=? may disregard the type of its arguments in +safe as well as not safe mode. +

+
+
([not] interrupts-enabled)
+
+

Generate (or don’t generate) interrupt checks. Interrupt checks are +used to detect user interrupts and also to check for stack overflows. +Interrupt checking should not be turned off casually. +

+
+
([not] debug)
+
+ +

Enable (or disable) the generation of debugging information. The kind +of debugging information that is generated depends on the declarations +debug-location, debug-source, and +debug-environments. If any of the command line options +-debug, -debug-location, -debug-source and +-debug-environments are present, the debug declaration +is initially enabled, otherwise it is initially disabled. When all +kinds of debugging information are generated there is a substantial +increase in the C compilation time and the size of the generated code. +When compiling a 3000 line Scheme file it was observed that the total +compilation time is 500% longer and the executable code is 150% +bigger. +

+
+
([not] debug-location)
+
+ +

Select (or deselect) source code location debugging information. When +this declaration and the debug declaration are in effect, run +time error messages indicate the location of the error in the source +code file. If any of the command line options -debug-source +and -debug-environments are present and -debug-location +is absent, the debug-location declaration is initially +disabled, otherwise it is initially enabled. When compiling a 3000 +line Scheme file it was observed that the total compilation time is +200% longer and the executable code is 60% bigger. +

+
+
([not] debug-source)
+
+ +

Select (or deselect) source code debugging information. When this +declaration and the debug declaration are in effect, run time +error messages indicate the source code, the backtraces are more +precise, and the pp procedure will display the source code of +compiled procedures. If any of the command line options +-debug-location and -debug-environments are present and +-debug-source is absent, the debug-source declaration is +initially disabled, otherwise it is initially enabled. When compiling +a 3000 line Scheme file it was observed that the total compilation +time is 90% longer and the executable code is 90% bigger. +

+
+
([not] debug-environments)
+
+ +

Select (or deselect) environment debugging information. When this +declaration and the debug declaration are in effect, the +debugger will have access to the environments of the continuations. +In other words the local variables defined in compiled procedures (and +not optimized away by the compiler) will be shown by the ,e +REPL command. If any of the command line options +-debug-location and -debug-source are present and +-debug-environments is absent, the debug-environments +declaration is initially disabled, otherwise it is initially enabled. +When compiling a 3000 line Scheme file it was observed that the total +compilation time is 70% longer and the executable code is 40% bigger. +

+
+
([not] proper-tail-calls)
+
+ + +

Generate (or don’t generate) proper tail calls. When proper tail +calls are turned off, tail calls are handled like non-tail calls, that +is a continuation frame will be created for all calls regardless of +their kind. This is useful for debugging because the caller of a +procedure will be visible in the backtrace produced by the REPL’s +,b command even when the call is a tail call. Be advised that +this does cause stack space to be consumed for tail calls which may +cause the stack to overflow when performing long iterations with tail +calls (whether they are expressed with a letrec, named +let, do, or other form). +

+
+
([not] optimize-dead-local-variables)
+
+

Remove (or preserve) the dead local variables in the environment. +Preserving the dead local variables is useful for debugging because +continuations will contain the dead variables. Thus, if the code is +also compiled with the declaration debug-environments +the ,e, ,ed, ,be, and ,bed REPL +commands will display the dead variables. On the other hand, +preserving the dead local variables may change the space complexity of +the program (i.e. some of the data that would normally be reclaimed by +the garbage collector will not be). Note that due to other compiler +optimizations some dead local variables may be removed regardless of +this declaration. +

+
+
(number-type primitive…)
+
+ + +

Numeric arguments and result of the specified primitives are +known to be of the given type (all primitives if none specified). +number-type can be: generic, fixnum, or +flonum. +

+
+
(mostly-number-type primitive…)
+
+ + + + +

Numeric arguments and result of the specified primitives are expected +to be most often of the given type (all primitives if none specified). +mostly-number-type can be: mostly-generic, +mostly-fixnum, mostly-fixnum-flonum, +mostly-flonum, or mostly-flonum-fixnum. +

+
+
+ +

The default declarations used by the compiler are equivalent to: +

+
 
(declare
+  (gambit-scheme)
+  (separate)
+  (inline)
+  (inline-primitives)
+  (inlining-limit 350)
+  (constant-fold)
+  (lambda-lift)
+  (not standard-bindings)
+  (not extended-bindings)
+  (run-time-bindings)
+  (safe)
+  (interrupts-enabled)
+  (not debug)           ;; depends on debugging command line options
+  (debug-location)      ;; depends on debugging command line options
+  (debug-source)        ;; depends on debugging command line options
+  (debug-environments)  ;; depends on debugging command line options
+  (proper-tail-calls)
+  (optimize-dead-local-variables)
+  (generic)
+  (mostly-fixnum-flonum)
+)
+
+ +

These declarations are compatible with the semantics of R5RS Scheme +and includes a few procedures from R6RS (mainly fixnum specific and +flonum specific procedures). Typically used declarations that enhance +performance, at the cost of violating the R5RS Scheme semantics, are: +(standard-bindings), (block), (not safe) and +(fixnum). +

+ + +
+ + + + + + + + + + + +
Back: 6.3 Miscellaneous extensionsForward: 7. Namespaces   FastBack: 6. Scheme extensionsUp: 6. Scheme extensionsFastForward: 7. NamespacesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

6.4 Undocumented extensions

+ +

The procedures in this section are not yet documented. +

+
(continuation? obj)procedure
+
(continuation-capture proc)procedure
+
(continuation-graft cont proc obj)procedure
+
(continuation-return cont obj)procedure
+ +

These procedures provide access to internal first-class continuations +which are represented using continuation objects distinct from procedures. +

+

The procedure continuation? returns #t when obj is +a continuation object and #f otherwise. +

+

The procedure continuation-capture is similar to the +call/cc procedure but it represents the continuation with a +continuation object. The proc parameter must be a procedure +accepting a single argument. The procedure +continuation-capture reifies its continuation and calls +proc with the corresponding continuation object as its sole +argument. Like for call/cc, the implicit continuation of the +call to proc is the implicit continuation of the call to +continuation-capture. +

+

The procedure continuation-graft performs a procedure call to +the procedure proc with arguments obj… and the +implicit continuation corresponding to the continuation object +cont. The current continuation of the call to procedure +continuation-graft is ignored. +

+

The procedure continuation-return invokes the implicit +continuation corresponding to the continuation object cont with +the result(s) obj…. This procedure can be easily +defined in terms of continuation-graft: +

+
 
(define (continuation-return cont . objs)
+  (continuation-graft (lambda () (apply values objs))))
+
+ +

For example: +

+
 
> (define x #f)
+> (define p (make-parameter 11))
+> (pp (parameterize ((p 22))
+        (cons 33 (continuation-capture
+                  (lambda (c) (set! x c) 44)))))
+(33 . 44)
+> x
+#<continuation #2>
+> (continuation-return x 55)
+(33 . 55)
+> (continuation-graft x (lambda () (expt 2 10)))
+(33 . 1024)
+> (continuation-graft x expt 2 10)
+(33 . 1024)
+> (continuation-graft x (lambda () (p)))
+(33 . 22)
+> (define (map-sqrt1 lst)
+    (call/cc
+     (lambda (k)
+       (map (lambda (x)
+              (if (< x 0)
+                  (k 'error)
+                  (sqrt x)))
+            lst))))
+> (map-sqrt1 '(1 4 9))
+(1 2 3)
+> (map-sqrt1 '(1 -1 9))
+error
+> (define (map-sqrt2 lst)
+    (continuation-capture
+     (lambda (c)
+       (map (lambda (x)
+              (if (< x 0)
+                  (continuation-return c 'error)
+                  (sqrt x)))
+            lst))))
+> (map-sqrt2 '(1 4 9))
+(1 2 3)
+> (map-sqrt2 '(1 -1 9))
+error
+
+ + + +
(display-exception exc [port])procedure
+
(display-exception-in-context exc cont [port])procedure
+
(display-procedure-environment proc [port])procedure
+
(display-continuation-environment cont [port])procedure
+
(display-continuation-dynamic-environment cont [port])procedure
+ + +
(display-continuation-backtrace cont [port [all-frames? [display-env? [max-head [max-tail [depth]]]]]])procedure
+ +

The procedure display-continuation-backtrace displays the +frames of the continuation corresponding to the continuation object +cont on the port port. If it is not specified, port +defaults to the current output-port. The frames are displayed in the +same format as the REPL’s ,b command. +

+

The parameter all-frames?, which defaults to #f, controls +which frames are displayed. Some frames of ancillary importance, such +as internal frames created by the interpreter, are not displayed when +all-frames? is #f. Otherwise all frames are displayed. +

+

The parameter display-env?, which defaults to #f, controls +if the frames are displayed with its environment (the variables +accessible and their bindings). +

+

The parameters max-head and max-tail, which default to 10 +and 4 respectively, control how many frames are displayed at the head +and tail of the continuation. +

+

The parameter depth, which defaults to 0, causes the frame numbers +to be offset by that value. +

+

For example: +

+
 
> (define x #f)
+> (define (fib n)
+    (if (< n 2)
+        (continuation-capture
+         (lambda (c) (set! x c) 1))
+        (+ (fib (- n 1))
+           (fib (- n 2)))))
+> (fib 10)
+89
+> (display-continuation-backtrace x)
+0  fib             (console)@7:12     (fib (- n 2))
+1  fib             (console)@7:12     (fib (- n 2))
+2  fib             (console)@7:12     (fib (- n 2))
+3  fib             (console)@7:12     (fib (- n 2))
+4  fib             (console)@7:12     (fib (- n 2))
+5  (interaction)   (console)@8:1      (fib 10)
+#f
+> (display-continuation-backtrace x (current-output-port) #t)
+0  fib             (console)@7:12     (fib (- n 2))
+1  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
+2  fib             (console)@7:12     (fib (- n 2))
+3  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
+4  fib             (console)@7:12     (fib (- n 2))
+5  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
+6  fib             (console)@7:12     (fib (- n 2))
+7  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
+8  fib             (console)@7:12     (fib (- n 2))
+9  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
+...
+13 ##with-no-result-expected-toplevel 
+14 ##repl-debug            
+15 ##repl-debug-main       
+16 ##kernel-handlers       
+#f
+> (display-continuation-backtrace x (current-output-port) #f #t)
+0  fib             (console)@7:12     (fib (- n 2))
+        n = 2
+1  fib             (console)@7:12     (fib (- n 2))
+        n = 4
+2  fib             (console)@7:12     (fib (- n 2))
+        n = 6
+3  fib             (console)@7:12     (fib (- n 2))
+        n = 8
+4  fib             (console)@7:12     (fib (- n 2))
+        n = 10
+5  (interaction)   (console)@8:1      (fib 10)
+#f
+> (display-continuation-backtrace x (current-output-port) #f #f 2 1 100)
+100 fib            (console)@7:12     (fib (- n 2))
+101 fib            (console)@7:12     (fib (- n 2))
+...
+105 (interaction)  (console)@8:1      (fib 10)
+#f
+
+ + + +
(make-thread-group [name [thread-group]])procedure
+
(thread-group? obj)procedure
+
(thread-group-name thread-group)procedure
+
(thread-group-parent thread-group)procedure
+
(thread-group-resume! thread-group)procedure
+
(thread-group-suspend! thread-group)procedure
+
(thread-group-terminate! thread-group)procedure
+
(thread-group->thread-group-list thread-group)procedure
+
(thread-group->thread-group-vector thread-group)procedure
+
(thread-group->thread-list thread-group)procedure
+
(thread-group->thread-vector thread-group)procedure
+ + +
(thread-state thread)procedure
+
(thread-state-uninitialized? thread-state)procedure
+
(thread-state-initialized? thread-state)procedure
+
(thread-state-active? thread-state)procedure
+
(thread-state-active-waiting-for thread-state)procedure
+
(thread-state-active-timeout thread-state)procedure
+
(thread-state-normally-terminated? thread-state)procedure
+
(thread-state-normally-terminated-result thread-state)procedure
+
(thread-state-abnormally-terminated? thread-state)procedure
+
(thread-state-abnormally-terminated-reason thread-state)procedure
+
(top [thread-group [port]])procedure
+ + +
(thread-interrupt! thread [thunk])procedure
+ + +
(thread-suspend! thread)procedure
+
(thread-resume! thread)procedure
+ + +
(thread-thread-group thread)procedure
+ + +
(define-type-of-thread name field)special form
+ + +
(thread-init! thread thunk [name [thread-group]])procedure
+ + +
(initialized-thread-exception? obj)procedure
+
(initialized-thread-exception-procedure exc)procedure
+
(initialized-thread-exception-arguments exc)procedure
+ + +
(uninitialized-thread-exception? obj)procedure
+
(uninitialized-thread-exception-procedure exc)procedure
+
(uninitialized-thread-exception-arguments exc)procedure
+ + +
(inactive-thread-exception? obj)procedure
+
(inactive-thread-exception-procedure exc)procedure
+
(inactive-thread-exception-arguments exc)procedure
+ + +
(rpc-remote-error-exception? obj)procedure
+
(rpc-remote-error-exception-procedure exc)procedure
+
(rpc-remote-error-exception-arguments exc)procedure
+
(rpc-remote-error-exception-message exc)procedure
+ + +
(timeout->time timeout)procedure
+ + +
(open-dummy)procedure
+ + +
(port-settings-set! port settings)procedure
+ + +
(input-port-bytes-buffered port)procedure
+ + +
(input-port-characters-buffered port)procedure
+ + +
(nonempty-input-port-character-buffer-exception? obj)procedure
+
(nonempty-input-port-character-buffer-exception-arguments exc)procedure
+
(nonempty-input-port-character-buffer-exception-procedure exc)procedure
+ + +
(repl-input-port)procedure
+
(repl-output-port)procedure
+
(console-port)procedure
+ + +
(current-user-interrupt-handler [handler])procedure
+
(defer-user-interrupts)procedure
+ + +
(primordial-exception-handler exc)procedure
+ + +
(err-code->string code)procedure
+ + +
(foreign? obj)procedure
+
(foreign-tags foreign)procedure
+
(foreign-address foreign)procedure
+
(foreign-release! foreign)procedure
+
(foreign-released? foreign)procedure
+ + +
(invalid-hash-number-exception? obj)procedure
+
(invalid-hash-number-exception-procedure exc)procedure
+
(invalid-hash-number-exception-arguments exc)procedure
+ + +
(tcp-client-peer-socket-info tcp-client-port)procedure
+
(tcp-client-self-socket-info tcp-client-port)procedure
+ + +
(tcp-server-socket-info tcp-server-port)procedure
+ + +
(socket-info? obj)procedure
+
(socket-info-address socket-info)procedure
+
(socket-info-family socket-info)procedure
+
(socket-info-port-number socket-info)procedure
+ + +
(system-version)procedure
+
(system-version-string)procedure
+ + +
(system-type)procedure
+
(system-type-string)procedure
+
(configure-command-string)procedure
+ + +
(system-stamp)procedure
+ + +
(future expr)special form
+
(touch obj)procedure
+ + +
(tty? obj)procedure
+
(tty-history tty)procedure
+
(tty-history-set! tty history)procedure
+
(tty-history-max-length-set! tty n)procedure
+
(tty-paren-balance-duration-set! tty duration)procedure
+
(tty-text-attributes-set! tty attributes)procedure
+
(tty-mode-set! tty mode)procedure
+
(tty-type-set! tty type)procedure
+ + +
(with-input-from-port port thunk)procedure
+
(with-output-to-port port thunk)procedure
+ + +
(input-port-char-position port)procedure
+
(output-port-char-position port)procedure
+ + +
(open-event-queue n)procedure
+ + +
(main)procedure
+ + +
(define-record-type)special form
+
(define-type)special form
+ + +
(namespace)special form
+ + +
(this-source-file)special form
+ + +
(receive)special form
+ + +
(cond-expand)special form
+ + +
(define-cond-expand-feature ident)special form
+ + +
(finite? x)procedure
+
(infinite? x)procedure
+
(nan? x)procedure
+ + +
(six.!)undefined
+
(six.!x x)special form
+
(six.&x x)special form
+
(six.*x x)special form
+
(six.++x x)special form
+
(six.+x x)special form
+
(six.--x x)special form
+
(six.-x x)special form
+
(six.arrow expr ident)special form
+
(six.break)undefined
+
(six.call func arg)special form
+
(six.case)undefined
+
(six.clause)undefined
+
(six.compound statement)special form
+
(six.cons x y)special form
+
(six.continue)undefined
+
(six.define-procedure ident proc)special form
+
(six.define-variable ident type dims init)special form
+
(six.do-while stat expr)special form
+
(six.dot expr ident)special form
+
(six.for stat1 expr2 expr3 stat2)special form
+
(six.goto)undefined
+
(six.identifier ident)special form
+
(six.if expr stat1 [stat2])special form
+
(six.index expr1 expr2)special form
+
(six.label)undefined
+
(six.list x y)special form
+
(six.literal value)special form
+
(six.make-array init dim)procedure
+
(six.new ident arg)special form
+
(six.null)special form
+
(six.prefix datum)special form
+
(six.procedure type params stat)special form
+
(six.procedure-body stat)special form
+
(six.return)undefined
+
(six.switch)undefined
+
(six.while expr stat)special form
+
(six.x!=y x y)special form
+
(six.x%=y x y)special form
+
(six.x%y x y)special form
+
(six.x&&y x y)special form
+
(six.x&=y x y)special form
+
(six.x&y x y)special form
+
(six.x*=y x y)special form
+
(six.x*y x y)special form
+
(six.x++ x)special form
+
(six.x+=y x y)special form
+
(six.x+y x y)special form
+
(|six.x,y| x y)special form
+
(six.x-- x)special form
+
(six.x-=y x y)special form
+
(six.x-y x y)special form
+
(six.x/=y x y)special form
+
(six.x/y x y)special form
+
(six.x:-y x y)undefined
+
(six.x:=y x y)special form
+
(six.x:y x y)special form
+
(six.x<<=y x y)special form
+
(six.x<<y x y)special form
+
(six.x<=y x y)special form
+
(six.x<y x y)special form
+
(six.x==y x y)special form
+
(six.x=y x y)special form
+
(six.x>=y x y)special form
+
(six.x>>=y x y)special form
+
(six.x>>y x y)special form
+
(six.x>y x y)special form
+
(six.x?y:z x y z)special form
+
(six.x^=y x y)special form
+
(six.x^y x y)special form
+
(|six.x\|=y| x y)special form
+
(|six.x\|y| x y)special form
+
(|six.x\|\|y| x y)special form
+
(six.~x x)special form
+ + +
+ + + + + + + + + + + +
Back: 6.4 Undocumented extensionsForward: 8. Characters and strings   FastBack: 6. Scheme extensionsUp: Gambit-CFastForward: 8. Characters and stringsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

7. Namespaces

+ +

TO DO! +

+
+ + + + + + + + + + + +
Back: 7. NamespacesForward: 8.1 Extensions to character procedures   FastBack: 7. NamespacesUp: Gambit-CFastForward: 9. NumbersTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

8. Characters and strings

+ +

Gambit supports the Unicode character encoding standard. Scheme +characters can be any of the characters whose Unicode encoding is in +the range 0 to #x10ffff (inclusive) but not in the range #xd800 to +#xdfff. Source code can also contain any Unicode character, however +to read such source code properly gsi and gsc must be +told which character encoding to use for reading the source code +(i.e. ASCII, ISO-8859-1, UTF-8, etc). This can be done by specifying +the runtime option -:f when gsi and gsc are +started. +

+ + + + + +
+ + + + + + + + + + + +
Back: 8. Characters and stringsForward: 8.2 Extensions to string procedures   FastBack: 8. Characters and stringsUp: 8. Characters and stringsFastForward: 9. NumbersTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

8.1 Extensions to character procedures

+ +
(char->integer char)procedure
+
(integer->char n)procedure
+ +

The procedure char->integer returns the Unicode encoding of +the character char. +

+

The procedure integer->char returns the character whose +Unicode encoding is the exact integer n. +

+

For example: +

+
 
> (char->integer #\!)
+33
+> (integer->char 65)
+#\A
+> (integer->char (char->integer #\u1234))
+#\u1234
+> (integer->char #xd800)
+*** ERROR IN (console)@4.1 -- (Argument 1) Out of range
+(integer->char 55296)
+
+ + + +
(char=? char1)procedure
+
(char<? char1)procedure
+
(char>? char1)procedure
+
(char<=? char1)procedure
+
(char>=? char1)procedure
+
(char-ci=? char1)procedure
+
(char-ci<? char1)procedure
+
(char-ci>? char1)procedure
+
(char-ci<=? char1)procedure
+
(char-ci>=? char1)procedure
+ +

These procedures take any number of arguments including no argument. +This is useful to test if the elements of a list are sorted in a +particular order. For example, testing that the list of characters +lst is sorted in nondecreasing order can be done with the call +(apply char<? lst). +

+ + +
+ + + + + + + + + + + +
Back: 8.1 Extensions to character proceduresForward: 9. Numbers   FastBack: 8. Characters and stringsUp: 8. Characters and stringsFastForward: 9. NumbersTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

8.2 Extensions to string procedures

+ +
(string=? string1)procedure
+
(string<? string1)procedure
+
(string>? string1)procedure
+
(string<=? string1)procedure
+
(string>=? string1)procedure
+
(string-ci=? string1)procedure
+
(string-ci<? string1)procedure
+
(string-ci>? string1)procedure
+
(string-ci<=? string1)procedure
+
(string-ci>=? string1)procedure
+ +

These procedures take any number of arguments including no argument. +This is useful to test if the elements of a list are sorted in a +particular order. For example, testing that the list of strings +lst is sorted in nondecreasing order can be done with the call +(apply string<? lst). +

+ + +
+ + + + + + + + + + + +
Back: 8.2 Extensions to string proceduresForward: 9.1 Extensions to numeric procedures   FastBack: 8. Characters and stringsUp: Gambit-CFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9. Numbers

+ + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 9. NumbersForward: 9.2 IEEE floating point arithmetic   FastBack: 9. NumbersUp: 9. NumbersFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9.1 Extensions to numeric procedures

+ +
(= z1)procedure
+
(< x1)procedure
+
(> x1)procedure
+
(<= x1)procedure
+
(>= x1)procedure
+ +

These procedures take any number of arguments including no argument. +This is useful to test if the elements of a list are sorted in a +particular order. For example, testing that the list of numbers +lst is sorted in nondecreasing order can be done with the call +(apply < lst). +

+ + +
+ + + + + + + + + + + +
Back: 9.1 Extensions to numeric proceduresForward: 9.3 Integer square root and nth root   FastBack: 9. NumbersUp: 9. NumbersFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9.2 IEEE floating point arithmetic

+ +

To better conform to IEEE floating point arithmetic the standard +numeric tower is extended with these special inexact reals: +

+
+
+inf.0
+

positive infinity +

+
-inf.0
+

negative infinity +

+
+nan.0
+

“not a number” +

+
-0.
+

negative zero (0. is the positive zero) +

+
+ +

The infinities and “not a number” are reals (i.e. (real? ++inf.0) is #t) but are not rational (i.e. (rational? ++inf.0) is #f). +

+

Both zeros are numerically equal (i.e. (= -0. 0.) is #t) +but are not equivalent (i.e. (eqv? -0. 0.) and (equal? +-0. 0.) are #f). All numerical comparisons with “not a +number”, including (= +nan.0 +nan.0), are #f. +

+
+ + + + + + + + + + + +
Back: 9.2 IEEE floating point arithmeticForward: 9.4 Bitwise-operations on exact integers   FastBack: 9. NumbersUp: 9. NumbersFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9.3 Integer square root and nth root

+ +
(integer-sqrt n)procedure
+ +

This procedure returns the integer part of the square root of the +nonnegative exact integer n. +

+

For example: +

+
 
> (integer-sqrt 123)
+11
+
+ + + +
(integer-nth-root n1 n2)procedure
+ +

This procedure returns the integer part of n1 raised to the +power 1/n2, where n1 is a nonnegative exact integer and +n2 is a positive exact integer. +

+

For example: +

+
 
> (integer-nth-root 100 3)
+4
+
+ + + +
+ + + + + + + + + + + +
Back: 9.3 Integer square root and nth rootForward: 9.5 Fixnum specific operations   FastBack: 9. NumbersUp: 9. NumbersFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9.4 Bitwise-operations on exact integers

+ +

The procedures defined in this section are compatible with the +withdrawn “Integer Bitwise-operation Library SRFI” (SRFI 33). Note +that some of the procedures specified in SRFI 33 are not provided. +

+

Most procedures in this section are specified in terms of the binary +representation of exact integers. The two’s complement representation +is assumed where an integer is composed of an infinite number of bits. +The upper section of an integer (the most significant bits) are either +an infinite sequence of ones when the integer is negative, or they are +an infinite sequence of zeros when the integer is nonnegative. +

+
(arithmetic-shift n1 n2)procedure
+ +

This procedure returns n1 shifted to the left by n2 bits, +that is (floor (* n1 (expt 2 n2))). Both n1 +and n2 must be exact integers. +

+

For example: +

+
 
> (arithmetic-shift 1000 7)  ; n1=...0000001111101000
+128000
+> (arithmetic-shift 1000 -6) ; n1=...0000001111101000
+15
+> (arithmetic-shift -23 -3)  ; n1=...1111111111101001
+-3
+
+ + + +
(bitwise-merge n1 n2 n3)procedure
+ +

This procedure returns an exact integer whose bits combine the bits +from n2 and n3 depending on n1. The bit at index +i of the result depends only on the bits at index i in +n1, n2 and n3: it is equal to the bit in n2 +when the bit in n1 is 0 and it is equal to the bit in n3 +when the bit in n1 is 1. All arguments must be exact integers. +

+

For example: +

+
 
> (bitwise-merge -4 -11 10) ; ...11111100 ...11110101 ...00001010
+9
+> (bitwise-merge 12 -11 10) ; ...00001100 ...11110101 ...00001010
+-7
+
+ + + +
(bitwise-and n)procedure
+ +

This procedure returns the bitwise “and” of the exact integers +n…. The value -1 is returned when there are no arguments. +

+

For example: +

+
 
> (bitwise-and 6 12)  ; ...00000110 ...00001100
+4
+> (bitwise-and 6 -4)  ; ...00000110 ...11111100
+4
+> (bitwise-and -6 -4) ; ...11111010 ...11111100
+-8
+> (bitwise-and)
+-1
+
+ + + +
(bitwise-ior n)procedure
+ +

This procedure returns the bitwise “inclusive-or” of the exact +integers n…. The value 0 is returned when there are no +arguments. +

+

For example: +

+
 
> (bitwise-ior 6 12)  ; ...00000110 ...00001100
+14
+> (bitwise-ior 6 -4)  ; ...00000110 ...11111100
+-2
+> (bitwise-ior -6 -4) ; ...11111010 ...11111100
+-2
+> (bitwise-ior)
+0
+
+ + + +
(bitwise-xor n)procedure
+ +

This procedure returns the bitwise “exclusive-or” of the exact +integers n…. The value 0 is returned when there are no +arguments. +

+

For example: +

+
 
> (bitwise-xor 6 12)  ; ...00000110 ...00001100
+10
+> (bitwise-xor 6 -4)  ; ...00000110 ...11111100
+-6
+> (bitwise-xor -6 -4) ; ...11111010 ...11111100
+6
+> (bitwise-xor)
+0
+
+ + + +
(bitwise-not n)procedure
+ +

This procedure returns the bitwise complement of the exact integer +n. +

+

For example: +

+
 
> (bitwise-not 3)  ; ...00000011
+-4
+> (bitwise-not -1) ; ...11111111
+0
+
+ + + +
(bit-count n)procedure
+ +

This procedure returns the bit count of the exact integer n. If +n is nonnegative, the bit count is the number of 1 bits in the +two’s complement representation of n. If n is negative, +the bit count is the number of 0 bits in the two’s complement +representation of n. +

+

For example: +

+
 
> (bit-count 0)   ; ...00000000
+0
+> (bit-count 1)   ; ...00000001
+1
+> (bit-count 2)   ; ...00000010
+1
+> (bit-count 3)   ; ...00000011
+2
+> (bit-count 4)   ; ...00000100
+1
+> (bit-count -23) ; ...11101001
+3
+
+ + + +
(integer-length n)procedure
+ +

This procedure returns the bit length of the exact integer n. +If n is a positive integer the bit length is one more than the +index of the highest 1 bit (the least significant bit is at index 0). +If n is a negative integer the bit length is one more than the +index of the highest 0 bit. If n is zero, the bit length is 0. +

+

For example: +

+
 
> (integer-length 0)   ; ...00000000
+0
+> (integer-length 1)   ; ...00000001
+1
+> (integer-length 2)   ; ...00000010
+2
+> (integer-length 3)   ; ...00000011
+2
+> (integer-length 4)   ; ...00000100
+3
+> (integer-length -23) ; ...11101001
+5
+
+ + + +
(bit-set? n1 n2)procedure
+ +

This procedure returns a boolean indicating if the bit at index +n1 of n2 is set (i.e. equal to 1) or not. Both n1 +and n2 must be exact integers, and n1 must be +nonnegative. +

+

For example: +

+
 
> (map (lambda (i) (bit-set? i -23)) ; ...11101001
+       '(7 6 5 4 3 2 1 0))
+(#t #t #t #f #t #f #f #t)
+
+ + + +
(any-bits-set? n1 n2)procedure
+ +

This procedure returns a boolean indicating if the bitwise and +of n1 and n2 is different from zero or not. This procedure +is implemented more efficiently than the naive definition: +

+
 
(define (any-bits-set? n1 n2) (not (zero? (bitwise-and n1 n2))))
+
+ +

For example: +

+
 
> (any-bits-set? 5 10)   ; ...00000101 ...00001010
+#f
+> (any-bits-set? -23 32) ; ...11101001 ...00100000
+#t
+
+ + + +
(all-bits-set? n1 n2)procedure
+ +

This procedure returns a boolean indicating if the bitwise and +of n1 and n2 is equal to n1 or not. This procedure +is implemented more efficiently than the naive definition: +

+
 
(define (all-bits-set? n1 n2) (= n1 (bitwise-and n1 n2)))
+
+ +

For example: +

+
 
> (all-bits-set? 1 3) ; ...00000001 ...00000011
+#t
+> (all-bits-set? 7 3) ; ...00000111 ...00000011
+#f
+
+ + + +
(first-bit-set n)procedure
+ +

This procedure returns the bit index of the least significant bit of +n equal to 1 (which is also the number of 0 bits that are below +the least significant 1 bit). This procedure returns -1 when +n is zero. +

+

For example: +

+
 
> (first-bit-set 24) ; ...00011000
+3
+> (first-bit-set 0)  ; ...00000000
+-1
+
+ + + +
(extract-bit-field n1 n2 n3)procedure
+
(test-bit-field? n1 n2 n3)procedure
+
(clear-bit-field n1 n2 n3)procedure
+
(replace-bit-field n1 n2 n3 n4)procedure
+
(copy-bit-field n1 n2 n3 n4)procedure
+ +

These procedures operate on a bit-field which is n1 bits wide +starting at bit index n2. All arguments must be exact integers +and n1 and n2 must be nonnegative. +

+

The procedure extract-bit-field returns the bit-field of +n3 shifted to the right so that the least significant bit of the +bit-field is the least significant bit of the result. +

+

The procedure test-bit-field? returns #t if any bit in +the bit-field of n3 is equal to 1, otherwise #f is +returned. +

+

The procedure clear-bit-field returns n3 with all bits +in the bit-field replaced with 0. +

+

The procedure replace-bit-field returns n4 with the +bit-field replaced with the least-significant n1 bits of +n3. +

+

The procedure copy-bit-field returns n4 with the +bit-field replaced with the (same index and size) bit-field in +n3. +

+

For example: +

+
 
> (extract-bit-field 5 2 -37)    ; ...11011011
+22
+> (test-bit-field? 5 2 -37)      ; ...11011011
+#t
+> (test-bit-field? 1 2 -37)      ; ...11011011
+#f
+> (clear-bit-field 5 2 -37)      ; ...11011011
+-125
+> (replace-bit-field 5 2 -6 -37) ; ...11111010 ...11011011
+-21
+> (copy-bit-field 5 2 -6 -37)    ; ...11111010 ...11011011
+-5
+
+ + + +
+ + + + + + + + + + + +
Back: 9.4 Bitwise-operations on exact integersForward: 9.6 Flonum specific operations   FastBack: 9. NumbersUp: 9. NumbersFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9.5 Fixnum specific operations

+ +
(fixnum? obj)procedure
+ + +
(fx* n1)procedure
+ + +
(fx+ n1)procedure
+ + +
(fx- n1 n2)procedure
+ + +
(fx< n1)procedure
+ + +
(fx<= n1)procedure
+ + +
(fx= n1)procedure
+ + +
(fx> n1)procedure
+ + +
(fx>= n1)procedure
+ + +
(fxabs n)procedure
+ + +
(fxand n1)procedure
+ + +
(fxarithmetic-shift n1 n2)procedure
+ + +
(fxarithmetic-shift-left n1 n2)procedure
+ + +
(fxarithmetic-shift-right n1 n2)procedure
+ + +
(fxbit-count n)procedure
+ + +
(fxbit-set? n1 n2)procedure
+ + +
(fxeven? n)procedure
+ + +
(fxfirst-bit-set n)procedure
+ + +
(fxif n1 n2 n3)procedure
+ + +
(fxior n1)procedure
+ + +
(fxlength n)procedure
+ + +
(fxmax n1 n2)procedure
+ + +
(fxmin n1 n2)procedure
+ + +
(fxmodulo n1 n2)procedure
+ + +
(fxnegative? n)procedure
+ + +
(fxnot n)procedure
+ + +
(fxodd? n)procedure
+ + +
(fxpositive? n)procedure
+ + +
(fxquotient n1 n2)procedure
+ + +
(fxremainder n1 n2)procedure
+ + +
(fxwrap* n1)procedure
+ + +
(fxwrap+ n1)procedure
+ + +
(fxwrap- n1 n2)procedure
+ + +
(fxwrapabs n)procedure
+ + +
(fxwraparithmetic-shift n1 n2)procedure
+ + +
(fxwraparithmetic-shift-left n1 n2)procedure
+ + +
(fxwraplogical-shift-right n1 n2)procedure
+ + +
(fxwrapquotient n1 n2)procedure
+ + +
(fxxor n1)procedure
+ + +
(fxzero? n)procedure
+ + +
(fixnum-overflow-exception? obj)procedure
+
(fixnum-overflow-exception-procedure exc)procedure
+
(fixnum-overflow-exception-arguments exc)procedure
+ +

Fixnum-overflow-exception objects are raised by some of the fixnum +specific procedures when the result is larger than can fit in a +fixnum. The parameter exc must be a fixnum-overflow-exception +object. +

+

The procedure fixnum-overflow-exception? returns +#t when obj is a fixnum-overflow-exception +object and #f otherwise. +

+

The procedure fixnum-overflow-exception-procedure +returns the procedure that raised exc. +

+

The procedure fixnum-overflow-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (fixnum-overflow-exception? exc)
+        (list (fixnum-overflow-exception-procedure exc)
+              (fixnum-overflow-exception-arguments exc))
+        'not-fixnum-overflow-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (fx* 100000 100000)))
+(#<procedure #2 fx*> (100000 100000))
+
+ + + +
+ + + + + + + + + + + +
Back: 9.5 Fixnum specific operationsForward: 9.7 Pseudo random numbers   FastBack: 9. NumbersUp: 9. NumbersFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9.6 Flonum specific operations

+ +
(flonum? obj)procedure
+ + +
(fixnum->flonum n)procedure
+ + +
(fl* x1)procedure
+ + +
(fl+ x1)procedure
+ + +
(fl- x1 x2)procedure
+ + +
(fl/ x1 x2)procedure
+ + +
(fl< x1)procedure
+ + +
(fl<= x1)procedure
+ + +
(fl= x1)procedure
+ + +
(fl> x1)procedure
+ + +
(fl>= x1)procedure
+ + +
(flabs x)procedure
+ + +
(flacos x)procedure
+ + +
(flasin x)procedure
+ + +
(flatan x)procedure
+
(flatan y x)procedure
+ + +
(flceiling x)procedure
+ + +
(flcos x)procedure
+ + +
(fldenominator x)procedure
+ + +
(fleven? x)procedure
+ + +
(flexp x)procedure
+ + +
(flexpt x y)procedure
+ + +
(flfinite? x)procedure
+ + +
(flfloor x)procedure
+ + +
(flinfinite? x)procedure
+ + +
(flinteger? x)procedure
+ + +
(fllog x)procedure
+ + +
(flmax x1 x2)procedure
+ + +
(flmin x1 x2)procedure
+ + +
(flnan? x)procedure
+ + +
(flnegative? x)procedure
+ + +
(flnumerator x)procedure
+ + +
(flodd? x)procedure
+ + +
(flpositive? x)procedure
+ + +
(flround x)procedure
+ + +
(flsin x)procedure
+ + +
(flsqrt x)procedure
+ + +
(fltan x)procedure
+ + +
(fltruncate x)procedure
+ + +
(flzero? x)procedure
+ + +
+ + + + + + + + + + + +
Back: 9.6 Flonum specific operationsForward: 10. Homogeneous vectors   FastBack: 9. NumbersUp: 9. NumbersFastForward: 10. Homogeneous vectorsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

9.7 Pseudo random numbers

+ +

The procedures and variables defined in this section are compatible +with the “Sources of Random Bits SRFI” (SRFI 27). The +implementation is based on Pierre L’Ecuyer’s MRG32k3a pseudo random +number generator. At the heart of SRFI 27’s interface is the random +source type which encapsulates the state of a pseudo random number +generator. The state of a random source object changes every time a +pseudo random number is generated from this random source object. +

+
(default-random-source)variable
+ +

The global variable default-random-source is bound to the +random source object which is used by the random-integer, +random-real, random-u8vector and random-f64vector +procedures. +

+ + +
(random-integer n)procedure
+ +

This procedure returns a pseudo random exact integer in the range 0 to +n-1. The random source object in the global variable +default-random-source is used to generate this number. The +parameter n must be a positive exact integer. +

+

For example: +

+
 
> (random-integer 100)
+24
+> (random-integer 100)
+2
+> (random-integer 10000000000000000000000000000000000000000)
+6143360270902284438072426748425263488507
+
+ + + +
(random-real)procedure
+ +

This procedure returns a pseudo random inexact real between, but not +including, 0 and 1. The random source object in the global variable +default-random-source is used to generate this number. +

+

For example: +

+
 
> (random-real)
+.24230672079133753
+> (random-real)
+.02317001922506932
+
+ + + +
(random-u8vector n)procedure
+ +

This procedure returns a u8vector of length n containing pseudo +random exact integers in the range 0 to 255. The random source object +in the global variable default-random-source is used to +generate these numbers. The parameter n must be a nonnegative +exact integer. +

+

For example: +

+
 
> (random-u8vector 10)
+#u8(200 53 29 202 3 85 208 187 73 219)
+
+ + + +
(random-f64vector n)procedure
+ +

This procedure returns a f64vector of length n containing pseudo +random inexact reals between, but not including, 0 and 1. The random +source object in the global variable default-random-source is +used to generate these numbers. The parameter n must be a nonnegative +exact integer. +

+

For example: +

+
 
> (random-f64vector 3)
+#f64(.7145854494613069 .47089632669147946 .5400124875182746)
+
+ + + +
(make-random-source)procedure
+ +

This procedure returns a new random source object initialized to a +predetermined state (to initialize to a pseudo random state the +procedure random-source-randomize! should be called). +

+

For example: +

+
 
> (define rs (make-random-source))
+> ((random-source-make-integers rs) 10000000)
+8583952
+
+ + + +
(random-source? obj)procedure
+ +

This procedure returns #t when obj is a random source +object and #f otherwise. +

+

For example: +

+
 
> (random-source? default-random-source)
+#t
+> (random-source? 123)
+#f
+
+ + + +
(random-source-state-ref random-source)procedure
+
(random-source-state-set! random-source state)procedure
+ +

The procedure random-source-state-ref extracts the state of +the random source object random-source and returns a vector +containing the state. +

+

The procedure random-source-state-set! restores the state of +the random source object random-source to state which must +be a vector returned from a call to the procedure +random-source-state-ref. +

+

For example: +

+
 
> (define s (random-source-state-ref default-random-source))
+> (random-integer 10000000000000000000000000000000000000000)
+7583880188903074396261960585615270693321
+> (random-source-state-set! default-random-source s)
+> (random-integer 10000000000000000000000000000000000000000)
+7583880188903074396261960585615270693321
+
+ + + +
(random-source-randomize! random-source)procedure
+
(random-source-pseudo-randomize! random-source i j)procedure
+ +

These procedures change the state of the random source object +random-source. The procedure random-source-randomize! +sets the random source object to a state that depends on the current +time (which for typical uses can be considered to randomly initialize +the state). The procedure random-source-pseudo-randomize! +sets the random source object to a state that is determined only by +the current state and the nonnegative exact integers i and +j. For both procedures the value returned is unspecified. +

+

For example: +

+
 
> (define s (random-source-state-ref default-random-source))
+> (random-source-pseudo-randomize! default-random-source 5 99)
+> (random-integer 10000000000000000000000000000000000000000)
+9816755163910623041601722050112674079767
+> (random-source-state-set! default-random-source s)
+> (random-source-pseudo-randomize! default-random-source 5 99)
+> (random-integer 10000000000000000000000000000000000000000)
+9816755163910623041601722050112674079767
+> (random-source-pseudo-randomize! default-random-source 5 99)
+> (random-integer 10000000000000000000000000000000000000000)
+9816755163910623041601722050112674079767
+> (random-source-state-set! default-random-source s)
+> (random-source-randomize! default-random-source)
+> (random-integer 10000000000000000000000000000000000000000)
+2271441220851914333384493143687768110622
+> (random-source-state-set! default-random-source s)
+> (random-source-randomize! default-random-source)
+> (random-integer 10000000000000000000000000000000000000000)
+6247966138948323029033944059178072366895
+
+ + + +
(random-source-make-integers random-source)procedure
+ +

This procedure returns a procedure for generating pseudo random exact +integers using the random source object random-source. The +returned procedure accepts a single parameter n, a positive +exact integer, and returns a pseudo random exact integer in the range +0 to n-1. +

+

For example: +

+
 
> (define rs (make-random-source))
+> (define ri (random-source-make-integers rs))
+> (ri 10000000)
+8583952
+> (ri 10000000)
+2879793
+
+ + + +
(random-source-make-reals random-source [precision])procedure
+ +

This procedure returns a procedure for generating pseudo random +inexact reals using the random source object random-source. The +returned procedure accepts no parameters and returns a pseudo random +inexact real between, but not including, 0 and 1. The optional parameter +precision specifies an upper bound on the minimum amount by which two +generated pseudo-random numbers can be separated. +

+

For example: +

+
 
> (define rs (make-random-source))
+> (define rr (random-source-make-reals rs))
+> (rr)
+.857402537562821
+> (rr)
+.2876463473845367
+
+ + + +
(random-source-make-u8vectors random-source)procedure
+ +

This procedure returns a procedure for generating pseudo random +u8vectors using the random source object random-source. The +returned procedure accepts a single parameter n, a nonnegative +exact integer, and returns a u8vector of length n containing +pseudo random exact integers in the range 0 to 255. +

+

For example: +

+
 
> (define rs (make-random-source))
+> (define rv (random-source-make-u8vectors rs))
+> (rv 10)
+#u8(200 53 29 202 3 85 208 187 73 219)
+> (rv 10)
+#u8(113 8 182 120 138 103 53 192 40 176)
+
+ + + +
(random-source-make-f64vectors random-source [precision])procedure
+ +

This procedure returns a procedure for generating pseudo random +f64vectors using the random source object random-source. The +returned procedure accepts a single parameter n, a nonnegative +exact integer, and returns an f64vector of length n containing +pseudo random inexact reals between, but not including, 0 and 1. +The optional parameter precision specifies an upper bound on the +minimum amount by which two generated pseudo-random numbers can be separated. +

+

For example: +

+
 
> (define rs (make-random-source))
+> (define rv (random-source-make-f64vectors rs))
+> (rv 3)
+#f64(.7342236104231586 .2876463473845367 .8574025375628211)
+> (rv 3)
+#f64(.013863292728449427 .33449296573515447 .8162050798467028)
+
+ + + +
+ + + + + + + + + + + +
Back: 9.7 Pseudo random numbersForward: 11. Hashing and weak references   FastBack: 9. NumbersUp: Gambit-CFastForward: 11. Hashing and weak referencesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

10. Homogeneous vectors

+ + +

Homogeneous vectors are vectors containing raw numbers of the same +type (signed or unsigned exact integers or inexact reals). There are +10 types of homogeneous vectors: +s8vector (vector of exact integers in the range -2^7 to 2^7-1), +u8vector (vector of exact integers in the range 0 to 2^8-1), +s16vector (vector of exact integers in the range -2^15 to 2^15-1), +u16vector (vector of exact integers in the range 0 to 2^16-1), +s32vector (vector of exact integers in the range -2^31 to 2^31-1), +u32vector (vector of exact integers in the range 0 to 2^32-1), +s64vector (vector of exact integers in the range -2^63 to 2^63-1), +u64vector (vector of exact integers in the range 0 to 2^64-1), +f32vector (vector of 32 bit floating point numbers), +and f64vector (vector of 64 bit floating point numbers). +

+

The lexical syntax of homogeneous vectors is specified in +Homogeneous vector syntax. +

+

The procedures available for homogeneous vectors, listed below, are +the analog of the normal vector/string procedures for each of the +homogeneous vector types. +

+
(s8vector? obj)procedure
+
(make-s8vector k [fill])procedure
+
(s8vector exact-int8)procedure
+
(s8vector-length s8vector)procedure
+
(s8vector-ref s8vector k)procedure
+
(s8vector-set! s8vector k exact-int8)procedure
+
(s8vector->list s8vector)procedure
+
(list->s8vector list-of-exact-int8)procedure
+
(s8vector-fill! s8vector fill)procedure
+
(subs8vector-fill! vector start end fill)procedure
+
(append-s8vectors lst)procedure
+
(s8vector-copy s8vector)procedure
+
(s8vector-append s8vector)procedure
+
(subs8vector s8vector start end)procedure
+
(subs8vector-move! src-s8vector src-start src-end dst-s8vector dst-start)procedure
+
(s8vector-shrink! s8vector k)procedure
+ + +
(u8vector? obj)procedure
+
(make-u8vector k [fill])procedure
+
(u8vector exact-int8)procedure
+
(u8vector-length u8vector)procedure
+
(u8vector-ref u8vector k)procedure
+
(u8vector-set! u8vector k exact-int8)procedure
+
(u8vector->list u8vector)procedure
+
(list->u8vector list-of-exact-int8)procedure
+
(u8vector-fill! u8vector fill)procedure
+
(subu8vector-fill! vector start end fill)procedure
+
(append-u8vectors lst)procedure
+
(u8vector-copy u8vector)procedure
+
(u8vector-append u8vector)procedure
+
(subu8vector u8vector start end)procedure
+
(subu8vector-move! src-u8vector src-start src-end dst-u8vector dst-start)procedure
+
(u8vector-shrink! u8vector k)procedure
+ + +
(s16vector? obj)procedure
+
(make-s16vector k [fill])procedure
+
(s16vector exact-int16)procedure
+
(s16vector-length s16vector)procedure
+
(s16vector-ref s16vector k)procedure
+
(s16vector-set! s16vector k exact-int16)procedure
+
(s16vector->list s16vector)procedure
+
(list->s16vector list-of-exact-int16)procedure
+
(s16vector-fill! s16vector fill)procedure
+
(subs16vector-fill! vector start end fill)procedure
+
(append-s16vectors lst)procedure
+
(s16vector-copy s16vector)procedure
+
(s16vector-append s16vector)procedure
+
(subs16vector s16vector start end)procedure
+
(subs16vector-move! src-s16vector src-start src-end dst-s16vector dst-start)procedure
+
(s16vector-shrink! s16vector k)procedure
+ + +
(u16vector? obj)procedure
+
(make-u16vector k [fill])procedure
+
(u16vector exact-int16)procedure
+
(u16vector-length u16vector)procedure
+
(u16vector-ref u16vector k)procedure
+
(u16vector-set! u16vector k exact-int16)procedure
+
(u16vector->list u16vector)procedure
+
(list->u16vector list-of-exact-int16)procedure
+
(u16vector-fill! u16vector fill)procedure
+
(subu16vector-fill! vector start end fill)procedure
+
(append-u16vectors lst)procedure
+
(u16vector-copy u16vector)procedure
+
(u16vector-append u16vector)procedure
+
(subu16vector u16vector start end)procedure
+
(subu16vector-move! src-u16vector src-start src-end dst-u16vector dst-start)procedure
+
(u16vector-shrink! u16vector k)procedure
+ + +
(s32vector? obj)procedure
+
(make-s32vector k [fill])procedure
+
(s32vector exact-int32)procedure
+
(s32vector-length s32vector)procedure
+
(s32vector-ref s32vector k)procedure
+
(s32vector-set! s32vector k exact-int32)procedure
+
(s32vector->list s32vector)procedure
+
(list->s32vector list-of-exact-int32)procedure
+
(s32vector-fill! s32vector fill)procedure
+
(subs32vector-fill! vector start end fill)procedure
+
(append-s32vectors lst)procedure
+
(s32vector-copy s32vector)procedure
+
(s32vector-append s32vector)procedure
+
(subs32vector s32vector start end)procedure
+
(subs32vector-move! src-s32vector src-start src-end dst-s32vector dst-start)procedure
+
(s32vector-shrink! s32vector k)procedure
+ + +
(u32vector? obj)procedure
+
(make-u32vector k [fill])procedure
+
(u32vector exact-int32)procedure
+
(u32vector-length u32vector)procedure
+
(u32vector-ref u32vector k)procedure
+
(u32vector-set! u32vector k exact-int32)procedure
+
(u32vector->list u32vector)procedure
+
(list->u32vector list-of-exact-int32)procedure
+
(u32vector-fill! u32vector fill)procedure
+
(subu32vector-fill! vector start end fill)procedure
+
(append-u32vectors lst)procedure
+
(u32vector-copy u32vector)procedure
+
(u32vector-append u32vector)procedure
+
(subu32vector u32vector start end)procedure
+
(subu32vector-move! src-u32vector src-start src-end dst-u32vector dst-start)procedure
+
(u32vector-shrink! u32vector k)procedure
+ + +
(s64vector? obj)procedure
+
(make-s64vector k [fill])procedure
+
(s64vector exact-int64)procedure
+
(s64vector-length s64vector)procedure
+
(s64vector-ref s64vector k)procedure
+
(s64vector-set! s64vector k exact-int64)procedure
+
(s64vector->list s64vector)procedure
+
(list->s64vector list-of-exact-int64)procedure
+
(s64vector-fill! s64vector fill)procedure
+
(subs64vector-fill! vector start end fill)procedure
+
(append-s64vectors lst)procedure
+
(s64vector-copy s64vector)procedure
+
(s64vector-append s64vector)procedure
+
(subs64vector s64vector start end)procedure
+
(subs64vector-move! src-s64vector src-start src-end dst-s64vector dst-start)procedure
+
(s64vector-shrink! s64vector k)procedure
+ + +
(u64vector? obj)procedure
+
(make-u64vector k [fill])procedure
+
(u64vector exact-int64)procedure
+
(u64vector-length u64vector)procedure
+
(u64vector-ref u64vector k)procedure
+
(u64vector-set! u64vector k exact-int64)procedure
+
(u64vector->list u64vector)procedure
+
(list->u64vector list-of-exact-int64)procedure
+
(u64vector-fill! u64vector fill)procedure
+
(subu64vector-fill! vector start end fill)procedure
+
(append-u64vectors lst)procedure
+
(u64vector-copy u64vector)procedure
+
(u64vector-append u64vector)procedure
+
(subu64vector u64vector start end)procedure
+
(subu64vector-move! src-u64vector src-start src-end dst-u64vector dst-start)procedure
+
(u64vector-shrink! u64vector k)procedure
+ + +
(f32vector? obj)procedure
+
(make-f32vector k [fill])procedure
+
(f32vector inexact-real)procedure
+
(f32vector-length f32vector)procedure
+
(f32vector-ref f32vector k)procedure
+
(f32vector-set! f32vector k inexact-real)procedure
+
(f32vector->list f32vector)procedure
+
(list->f32vector list-of-inexact-real)procedure
+
(f32vector-fill! f32vector fill)procedure
+
(subf32vector-fill! vector start end fill)procedure
+
(append-f32vectors lst)procedure
+
(f32vector-copy f32vector)procedure
+
(f32vector-append f32vector)procedure
+
(subf32vector f32vector start end)procedure
+
(subf32vector-move! src-f32vector src-start src-end dst-f32vector dst-start)procedure
+
(f32vector-shrink! f32vector k)procedure
+ + +
(f64vector? obj)procedure
+
(make-f64vector k [fill])procedure
+
(f64vector inexact-real)procedure
+
(f64vector-length f64vector)procedure
+
(f64vector-ref f64vector k)procedure
+
(f64vector-set! f64vector k inexact-real)procedure
+
(f64vector->list f64vector)procedure
+
(list->f64vector list-of-inexact-real)procedure
+
(f64vector-fill! f64vector fill)procedure
+
(subf64vector-fill! vector start end fill)procedure
+
(append-f64vectors lst)procedure
+
(f64vector-copy f64vector)procedure
+
(f64vector-append f64vector)procedure
+
(subf64vector f64vector start end)procedure
+
(subf64vector-move! src-f64vector src-start src-end dst-f64vector dst-start)procedure
+
(f64vector-shrink! f64vector k)procedure
+ + +

For example: +

+
 
> (define v (u8vector 10 255 13))
+> (u8vector-set! v 2 99)
+> v
+#u8(10 255 99)
+> (u8vector-ref v 1)
+255
+> (u8vector->list v)
+(10 255 99)
+> (u8vector-shrink! v 2)
+> (v)
+#u8(10 255)
+
+ +
(object->u8vector obj [encoder])procedure
+
(u8vector->object u8vector [decoder])procedure
+ + + +

The procedure object->u8vector returns a u8vector that contains +the sequence of bytes that encodes the object obj. The +procedure u8vector->object decodes the sequence of bytes +contained in the u8vector u8vector, which was produced by the +procedure object->u8vector, and reconstructs an object +structurally equal to the original object. In other words the +procedures object->u8vector and u8vector->object +respectively perform serialization and deserialization of Scheme +objects. Note that some objects are non-serializable (e.g. threads, +wills, some types of ports, and any object containing a +non-serializable object). +

+

The optional encoder and decoder parameters are single +parameter procedures which default to the identity function. The +encoder procedure is called during serialization. As the +serializer walks through obj, it calls the encoder +procedure on each sub-object X that is encountered. The +encoder transforms the object X into an object Y +that will be serialized instead of X. Similarly the +decoder procedure is called during deserialization. When an +object Y is encountered, the decoder procedure is called +to transform it into the object X that is the result of +deserialization. +

+

The encoder and decoder procedures are useful to customize +the serialized representation of objects. In particular, it can be +used to define the semantics of serializing objects, such as threads +and ports, that would otherwise not be serializable. The +decoder procedure is typically the inverse of the encoder +procedure, i.e. (decoder (encoder X)) = +X. +

+

For example: +

+
 
> (define (make-adder x) (lambda (y) (+ x y)))
+> (define f (make-adder 10))
+> (define a (object->u8vector f))
+> (define b (u8vector->object a))
+> (u8vector-length a)
+1639
+> (f 5)
+15
+> (b 5)
+15
+> (pp b)
+(lambda (y) (+ x y))
+
+ + + +
+ + + + + + + + + + + +
Back: 10. Homogeneous vectorsForward: 11.1 Hashing   FastBack: 10. Homogeneous vectorsUp: Gambit-CFastForward: 12. RecordsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

11. Hashing and weak references

+ + + + + + + + + +
+ + + + + + + + + + + +
Back: 11. Hashing and weak referencesForward: 11.2 Weak references   FastBack: 11. Hashing and weak referencesUp: 11. Hashing and weak referencesFastForward: 12. RecordsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

11.1 Hashing

+ +
(object->serial-number obj)procedure
+
(serial-number->object n [default])procedure
+ +

All Scheme objects are uniquely identified with a serial number which +is a nonnegative exact integer. The object->serial-number procedure +returns the serial number of object obj. This serial number is +only allocated the first time the object->serial-number +procedure is called on that object. Objects which do not have an +external textual representation that can be read by the read +procedure, use an external textual representation that includes a +serial number of the form #n. Consequently, the +procedures write, pretty-print, etc will call the +object->serial-number procedure to get the serial number, and +this may cause the serial number to be allocated. +

+

The serial-number->object procedure takes an exact integer +parameter n and returns the object whose serial number is +n. If no object currently exists with that serial number, +default is returned if it is specified, otherwise an +unbound-serial-number-exception object is raised. The reader defines +the following abbreviation for calling serial-number->object: +the syntax #n, where n is a sequence of decimal +digits and it is not followed by = or #, +is equivalent to the list (serial-number->object n). +

+

For example: +

+
 
> (define z (list (lambda (x) (* x x)) (lambda (y) (/ 1 y))))
+> z
+(#<procedure #2> #<procedure #3>)
+> (#3 10)
+1/10
+> '(#3 10)
+((serial-number->object 3) 10)
+> car
+#<procedure #4 car>
+> (#4 z)
+#<procedure #2>
+
+ + + +
(unbound-serial-number-exception? obj)procedure
+
(unbound-serial-number-exception-procedure exc)procedure
+
(unbound-serial-number-exception-arguments exc)procedure
+ +

Unbound-serial-number-exception objects are raised by the procedure +serial-number->object when no object currently exists with that +serial number. The parameter exc must be an +unbound-serial-number-exception object. +

+

The procedure unbound-serial-number-exception? returns +#t when obj is a unbound-serial-number-exception +object and #f otherwise. +

+

The procedure unbound-serial-number-exception-procedure +returns the procedure that raised exc. +

+

The procedure unbound-serial-number-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (unbound-serial-number-exception? exc)
+        (list (unbound-serial-number-exception-procedure exc)
+              (unbound-serial-number-exception-arguments exc))
+        'not-unbound-serial-number-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (serial-number->object 1000)))
+(#<procedure #2 serial-number->object> (1000))
+
+ + + +
(symbol-hash symbol)procedure
+ +

The symbol-hash procedure returns the hash number of the symbol +symbol. The hash number is a small exact integer (fixnum). +When symbol is an interned symbol the value returned is the same +as (string=?-hash (symbol->string symbol)). +

+

For example: +

+
 
> (symbol-hash 'car)
+444471047
+
+ + + +
(keyword-hash keyword)procedure
+ +

The keyword-hash procedure returns the hash number of the +keyword keyword. The hash number is a small exact integer +(fixnum). When keyword is an interned keyword the value +returned is the same as (string=?-hash (keyword->string +keyword)). +

+

For example: +

+
 
> (keyword-hash car:)
+444471047
+
+ + + +
(string=?-hash string)procedure
+ +

The string=?-hash procedure returns the hash number of the +string string. The hash number is a small exact integer +(fixnum). For any two strings s1 and s2, (string=? +s1 s2) implies (= (string=?-hash s1) +(string=?-hash s2)). +

+

For example: +

+
 
> (string=?-hash "car")
+444471047
+
+ + + +
(string-ci=?-hash string)procedure
+ +

The string-ci=?-hash procedure returns the hash number of the +string string. The hash number is a small exact integer +(fixnum). For any two strings s1 and s2, (string-ci=? +s1 s2) implies (= (string-ci=?-hash s1) +(string-ci=?-hash s2)). +

+

For example: +

+
 
> (string-ci=?-hash "CaR")
+444471047
+
+ + + +
(eq?-hash obj)procedure
+ +

The eq?-hash procedure returns the hash number of the object +obj. The hash number is a small exact integer (fixnum). For +any two objects o1 and o2, (eq? o1 o2) +implies (= (eq?-hash o1) (eq?-hash o2)). +

+

For example: +

+
 
> (eq?-hash #t)
+536870910
+
+ + + +
(eqv?-hash obj)procedure
+ +

The eqv?-hash procedure returns the hash number of the object +obj. The hash number is a small exact integer (fixnum). For +any two objects o1 and o2, (eqv? o1 o2) +implies (= (eqv?-hash o1) (eqv?-hash o2)). +

+

For example: +

+
 
> (eqv?-hash 1.5)
+496387656
+
+ + + +
(equal?-hash obj)procedure
+ +

The equal?-hash procedure returns the hash number of the object +obj. The hash number is a small exact integer (fixnum). For +any two objects o1 and o2, (equal? o1 o2) +implies (= (equal?-hash o1) (equal?-hash o2)). +

+

For example: +

+
 
> (equal?-hash (list 1 2 3))
+442438567
+
+ + + +
+ + + + + + + + + + + +
Back: 11.1 HashingForward: 11.2.1 Wills   FastBack: 11. Hashing and weak referencesUp: 11. Hashing and weak referencesFastForward: 12. RecordsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

11.2 Weak references

+ +

The garbage collector is responsible for reclaiming objects that are +no longer needed by the program. This is done by analyzing the +reachability graph of all objects from the roots (i.e. the global +variables, the runnable threads, permanently allocated objects such as +procedures defined in a compiled file, nonexecutable wills, etc). If +a root or a reachable object X contains a reference to an object +Y then Y is reachable. As a general rule, unreachable +objects are reclaimed by the garbage collector. +

+

There are two types of references: strong references and weak +references. Most objects, including pairs, vectors, records and +closures, contain strong references. An object X is +strongly reachable if there is a path from the roots to X +that traverses only strong references. Weak references only occur in +wills and tables. There are two types of weak references: will-weak +references and table-weak references. If all paths from the roots to +an object Y traverse at least one table-weak reference, then +Y will be reclaimed by the garbage collector. The will-weak +references are used for finalization and are explained in the next +section. +

+ + + + + +
+ + + + + + + + + + + +
Back: 11.2 Weak referencesForward: 11.2.2 Tables   FastBack: 11. Hashing and weak referencesUp: 11.2 Weak referencesFastForward: 12. RecordsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

11.2.1 Wills

+ +

The following procedures implement the will data type. Will +objects provide support for finalization. A will is an object that +contains a will-weak reference to a testator object (the object +attached to the will), and a strong reference to an action +procedure which is a one parameter procedure which is called when the +will is executed. +

+
(make-will testator action)procedure
+
(will? obj)procedure
+
(will-testator will)procedure
+
(will-execute! will)procedure
+ +

The make-will procedure creates a will object with the given +testator object and action procedure. The will? +procedure tests if obj is a will object. The +will-testator procedure gets the testator object attached to +the will. The will-execute! procedure executes +will. +

+

A will becomes executable when its testator object is not +strongly reachable (i.e. the testator object is either +unreachable or only reachable using paths from the roots that traverse +at least one weak reference). Some objects, including symbols, small +exact integers (fixnums), booleans and characters, are considered to +be always strongly reachable. +

+

When the runtime system detects that a will has become executable the +current computation is interrupted, the will’s testator is set to +#f and the will’s action procedure is called with the will’s +testator as the sole argument. Currently only the garbage collector +detects when wills become executable but this may change in future +versions of Gambit (for example the compiler could perform an analysis +to infer will executability at compile time). The garbage collector +builds a list of all executable wills. Shortly after a garbage +collection, the action procedures of these wills will be called. The +link from the will to the action procedure is severed when the action +procedure is called. +

+

Note that the testator object will not be reclaimed during the garbage +collection that determined executability of the will. It is only when +an object is not reachable from the roots that it is reclaimed by the +garbage collector. +

+

A remarkable feature of wills is that an action procedure can +“resurrect” an object. An action procedure could for example assign +the testator object to a global variable or create a new will with the +same testator object. +

+

For example: +

+
 
> (define a (list 123))
+> (set-cdr! a a) ; create a circular list
+> (define b (vector a))
+> (define c #f)
+> (define w
+    (let ((obj a))
+      (make-will obj
+                 (lambda (x) ; x will be eq? to obj
+                   (display "executing action procedure")
+                   (newline)
+                   (set! c x)))))
+> (will? w)
+#t
+> (car (will-testator w))
+123
+> (##gc)
+> (set! a #f)
+> (##gc)
+> (set! b #f)
+> (##gc)
+executing action procedure
+> (will-testator w)
+#f
+> (car c)
+123
+
+ + + +
+ + + + + + + + + + + +
Back: 11.2.1 WillsForward: 12. Records   FastBack: 11. Hashing and weak referencesUp: 11.2 Weak referencesFastForward: 12. RecordsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

11.2.2 Tables

+ +

The following procedures implement the table data type. Tables +are heterogenous structures whose elements are indexed by keys which +are arbitrary objects. Tables are similar to association lists but +are abstract and the access time for large tables is typically smaller. +Each key contained in the table is bound to a value. The length of +the table is the number of key/value bindings it contains. New +key/value bindings can be added to a table, the value bound to a key +can be changed, and existing key/value bindings can be removed. +

+

The references to the keys can either be all strong or all table-weak +and the references to the values can either be all strong or all +table-weak. The garbage collector removes key/value bindings from a +table when 1) the key is a table-weak reference and the key is +unreachable or only reachable using paths from the roots that traverse +at least one table-weak reference, or 2) the value is a table-weak +reference and the value is unreachable or only reachable using paths +from the roots that traverse at least one table-weak reference. +Key/value bindings that are removed by the garbage collector are +reclaimed immediately. +

+

Although there are several possible ways of implementing tables, the +current implementation uses hashing with open-addressing. This is +space efficient and provides constant-time access. Hash tables are +automatically resized to maintain the load within specified bounds. +The load is the number of active entries (the length of the table) +divided by the total number of entries in the hash table. +

+

Tables are parameterized with a key comparison procedure. By default +the equal? procedure is used, but eq?, eqv?, +string=?, string-ci=?, or a user defined procedure can +also be used. To support arbitrary key comparison procedures, tables +are also parameterized with a hashing procedure accepting a key as its +single parameter and returning a fixnum result. The hashing procedure +hash must be consistent with the key comparison procedure +test, that is, for any two keys k1 and k2 in the +table, (test k1 k2) implies (= +(hash k1) (hash k2)). A default hashing +procedure consistent with the key comparison procedure is provided by +the system. The default hashing procedure generally gives good +performance when the key comparison procedure is eq?, +eqv?, equal?, string=?, and string-ci=?. +However, for user defined key comparison procedures, the default +hashing procedure always returns 0. This degrades the performance of +the table to a linear search. +

+

Tables can be compared for equality using the equal? procedure. +Two tables X and Y are considered equal by +equal? when they have the same weakness attributes, the same +key comparison procedure, the same hashing procedure, the same length, +and for all the keys k in X, (equal? +(table-ref X k) (table-ref Y k)). +

+
(make-table [size: size] [init: init] [weak-keys: weak-keys] [weak-values: weak-values] [test: test] [hash: hash] [min-load: min-load] [max-load: max-load])procedure
+ +

The procedure make-table returns a new table. The optional keyword +parameters specify various parameters of the table. +

+

The size parameter is a nonnegative exact integer indicating +the expected length of the table. The system uses size to +choose an appropriate initial size of the hash table so that it does not +need to be resized too often. +

+

The init parameter indicates a value that is associated to keys +that are not in the table. When init is not specified, no value +is associated to keys that are not in the table. +

+

The weak-keys and weak-values parameters are extended +booleans indicating respectively whether the keys and values are +table-weak references (true) or strong references (false). By default +the keys and values are strong references. +

+

The test parameter indicates the key comparison procedure. The +default key comparison procedure is equal?. The key comparison +procedures eq?, eqv?, equal?, string=?, +and string-ci=? are special because the system will use a +reasonably good hash procedure when none is specified. +

+

The hash parameter indicates the hash procedure. This procedure +must accept a single key parameter, return a fixnum, and be consistent +with the key comparison procedure. When hash is not specified, a +default hash procedure is used. The default hash procedure is +reasonably good when the key comparison procedure is eq?, +eqv?, equal?, string=?, or string-ci=?. +

+

The min-load and max-load parameters are real numbers that +indicate the minimum and maximum load of the table respectively. The +table is resized when adding or deleting a key/value binding would +bring the table’s load outside of this range. The min-load +parameter must be no less than 0.05 and the max-load parameter +must be no greater than 0.95. Moreover the difference between +min-load and max-load must be at least 0.20. When +min-load is not specified, the value 0.45 is used. When +max-load is not specified, the value 0.90 is used. +

+

For example: +

+
 
> (define t (make-table))
+> (table? t)
+#t
+> (table-length t)
+0
+> (table-set! t (list 1 2) 3)
+> (table-set! t (list 4 5) 6)
+> (table-ref t (list 1 2))
+3
+> (table-length t)
+2
+
+ + + +
(table? obj)procedure
+ +

The procedure table? returns #t when obj is a +table and #f otherwise. +

+

For example: +

+
 
> (table? (make-table))
+#t
+> (table? 123)
+#f
+
+ + + +
(table-length table)procedure
+ +

The procedure table-length returns the number of key/value +bindings contained in the table table. +

+

For example: +

+
 
> (define t (make-table weak-keys: #t))
+> (define x (list 1 2))
+> (define y (list 3 4))
+> (table-set! t x 111)
+> (table-set! t y 222)
+> (table-length t)
+2
+> (table-set! t x)
+> (table-length t)
+1
+> (##gc)
+> (table-length t)
+1
+> (set! y #f)
+> (##gc)
+> (table-length t)
+0
+
+ + + +
(table-ref table key [default])procedure
+ +

The procedure table-ref returns the value bound to the object +key in the table table. When key is not bound and +default is specified, default is returned. When +default is not specified but an init parameter was +specified when table was created, init is returned. +Otherwise an unbound-table-key-exception object is raised. +

+

For example: +

+
 
> (define t1 (make-table init: 999))
+> (table-set! t1 (list 1 2) 3)
+> (table-ref t1 (list 1 2))
+3
+> (table-ref t1 (list 4 5))
+999
+> (table-ref t1 (list 4 5) #f)
+#f
+> (define t2 (make-table))
+> (table-ref t2 (list 4 5))
+*** ERROR IN (console)@7.1 -- Unbound table key
+(table-ref '#<table #2> '(4 5))
+
+ + + +
(table-set! table key [value])procedure
+ +

The procedure table-set! binds the object key to +value in the table table. When value is not +specified, if table contains a binding for key then the +binding is removed from table. The procedure table-set! +returns an unspecified value. +

+

For example: +

+
 
> (define t (make-table))
+> (table-set! t (list 1 2) 3)
+> (table-set! t (list 4 5) 6)
+> (table-set! t (list 4 5))
+> (table-set! t (list 7 8))
+> (table-ref t (list 1 2))
+3
+> (table-ref t (list 4 5))
+*** ERROR IN (console)@7.1 -- Unbound table key
+(table-ref '#<table #2> '(4 5))
+
+ + + +
(table-search proc table)procedure
+ +

The procedure table-search searches the table table for a +key/value binding for which the two parameter procedure proc +returns a non false result. For each key/value binding visited by +table-search the procedure proc is called with the key as +the first parameter and the value as the second parameter. The +procedure table-search returns the first non false value +returned by proc, or #f if proc returned #f +for all key/value bindings in table. +

+

The order in which the key/value bindings are visited is unspecified +and may vary from one call of table-search to the next. While +a call to table-search is being performed on table, it is +an error to call any of the following procedures on table: +table-ref, table-set!, table-search, +table-for-each, table-copy, table-merge, +table-merge!, and table->list. It is also an error to +compare with equal? (directly or indirectly with member, +assoc, table-ref, etc.) an object that contains +table. All these procedures may cause table to be +reordered and resized. This restriction allows a more efficient +iteration over the key/value bindings. +

+

For example: +

+
 
> (define square (make-table))
+> (table-set! square 2 4)
+> (table-set! square 3 9)
+> (table-search (lambda (k v) (and (odd? k) v)) square)
+9
+
+ + + +
(table-for-each proc table)procedure
+ +

The procedure table-for-each calls the two parameter procedure +proc for each key/value binding in the table table. The +procedure proc is called with the key as the first parameter and +the value as the second parameter. The procedure table-for-each +returns an unspecified value. +

+

The order in which the key/value bindings are visited is unspecified +and may vary from one call of table-for-each to the next. +While a call to table-for-each is being performed on +table, it is an error to call any of the following procedures on +table: table-ref, table-set!, table-search, +table-for-each, and table->list. It is also an error to +compare with equal? (directly or indirectly with member, +assoc, table-ref, etc.) an object that contains +table. All these procedures may cause table to be +reordered and resized. This restriction allows a more efficient +iteration over the key/value bindings. +

+

For example: +

+
 
> (define square (make-table))
+> (table-set! square 2 4)
+> (table-set! square 3 9)
+> (table-for-each (lambda (k v) (write (list k v)) (newline)) square)
+(2 4)
+(3 9)
+
+ + + +
(table->list table)procedure
+ +

The procedure table->list returns an association list +containing the key/value bindings in the table table. Each +key/value binding yields a pair whose car field is the key and whose +cdr field is the value bound to that key. The order of the bindings +in the list is unspecified. +

+

For example: +

+
 
> (define square (make-table))
+> (table-set! square 2 4)
+> (table-set! square 3 9)
+> (table->list square)
+((3 . 9) (2 . 4))
+
+ + + +
(list->table list [size: size] [init: init] [weak-keys: weak-keys] [weak-values: weak-values] [test: test] [hash: hash] [min-load: min-load] [max-load: max-load])procedure
+ +

The procedure list->table returns a new table containing the +key/value bindings in the association list list. The optional +keyword parameters specify various parameters of the table and have +the same meaning as for the make-table procedure. +

+

Each element of list is a pair whose car field is a key and +whose cdr field is the value bound to that key. If a key appears more +than once in list (tested using the table’s key comparison +procedure) it is the first key/value binding in list that has +precedence. +

+

For example: +

+
 
> (define t (list->table '((b . 2) (a . 1) (c . 3) (a . 4))))
+> (table->list t)
+((a . 1) (b . 2) (c . 3))
+
+ + + +
(unbound-table-key-exception? obj)procedure
+
(unbound-table-key-exception-procedure exc)procedure
+
(unbound-table-key-exception-arguments exc)procedure
+ +

Unbound-table-key-exception objects are raised by the procedure +table-ref when the key does not have a binding in the table. +The parameter exc must be an unbound-table-key-exception object. +

+

The procedure unbound-table-key-exception? returns +#t when obj is a unbound-table-key-exception +object and #f otherwise. +

+

The procedure unbound-table-key-exception-procedure +returns the procedure that raised exc. +

+

The procedure unbound-table-key-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define t (make-table))
+> (define (handler exc)
+    (if (unbound-table-key-exception? exc)
+        (list (unbound-table-key-exception-procedure exc)
+              (unbound-table-key-exception-arguments exc))
+        'not-unbound-table-key-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (table-ref t '(1 2))))
+(#<procedure #2 table-ref> (#<table #3> (1 2)))
+
+ + + +
(table-copy table)procedure
+ +

The procedure table-copy returns a new table containing the +same key/value bindings as table and the same table parameters +(i.e. hash procedure, key comparison procedure, key and value +weakness, etc). +

+

For example: +

+
 
> (define t (list->table '((b . 2) (a . 1) (c . 3))))
+> (define x (table-copy t))
+> (table-set! t 'b 99)
+> (table->list t)
+((a . 1) (b . 99) (c . 3))
+> (table->list x)
+((a . 1) (b . 2) (c . 3))
+
+ + + +
(table-merge! table1 table2 [table2-takes-precedence?])procedure
+ +

The procedure table-merge! returns table1 after the +key/value bindings contained in table2 have been added to it. +When a key exists both in table1 and table2, then the +parameter table2-takes-precedence? indicates which binding will +be kept (the one in table1 if table2-takes-precedence? is +false, and the one in table2 otherwise). If +table2-takes-precedence? is not specified the binding in +table1 is kept. +

+

For example: +

+
 
> (define t1 (list->table '((a . 1) (b . 2) (c . 3))))
+> (define t2 (list->table '((a . 4) (b . 5) (z . 6))))
+> (table->list (table-merge! t1 t2))
+((a . 1) (b . 2) (c . 3) (z . 6))
+> (define t1 (list->table '((a . 1) (b . 2) (c . 3))))
+> (define t2 (list->table '((a . 4) (b . 5) (z . 6))))
+> (table->list (table-merge! t1 t2 #t))
+((a . 4) (b . 5) (c . 3) (z . 6))
+
+ + + +
(table-merge table1 table2 [table2-takes-precedence?])procedure
+ +

The procedure table-merge returns a copy of table1 +(created with table-copy) to which the key/value bindings +contained in table2 have been added using table-merge!. +When a key exists both in table1 and table2, then the +parameter table2-takes-precedence? indicates which binding will +be kept (the one in table1 if table2-takes-precedence? is +false, and the one in table2 otherwise). If +table2-takes-precedence? is not specified the binding in +table1 is kept. +

+

For example: +

+
 
> (define t1 (list->table '((a . 1) (b . 2) (c . 3))))
+> (define t2 (list->table '((a . 4) (b . 5) (z . 6))))
+> (table->list (table-merge t1 t2))
+((a . 1) (b . 2) (c . 3) (z . 6))
+> (table->list (table-merge t1 t2 #t))
+((a . 4) (b . 5) (c . 3) (z . 6))
+
+ + + +
+ + + + + + + + + + + +
Back: 11.2.2 TablesForward: 13. Threads   FastBack: 11. Hashing and weak referencesUp: Gambit-CFastForward: 13. ThreadsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

12. Records

+ +
(define-structure name field)special form
+ +

Record data types similar to Pascal records and C struct +types can be defined using the define-structure special form. +The identifier name specifies the name of the new data type. The +structure name is followed by k identifiers naming each field of +the record. The define-structure expands into a set of definitions +of the following procedures: +

+ + +

Record data types have a printed representation that includes the name +of the type and the name and value of each field. Record data types +can not be read by the read procedure. +

+

For example: +

+
 
> (define-structure point x y color)
+> (define p (make-point 3 5 'red))
+> p
+#<point #2 x: 3 y: 5 color: red>
+> (point-x p)
+3
+> (point-color p)
+red
+> (point-color-set! p 'black)
+> p
+#<point #2 x: 3 y: 5 color: black>
+
+ + + +
+ + + + + + + + + + + +
Back: 12. RecordsForward: 13.1 Introduction   FastBack: 12. RecordsUp: Gambit-CFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13. Threads

+ + +

Gambit supports the execution of multiple Scheme threads. These +threads are managed entirely by Gambit’s runtime and are not related +to the host operating system’s threads. Gambit’s runtime does not +currently take advantage of multiprocessors (i.e. at most one thread is +running). +

+ + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 13. ThreadsForward: 13.2 Thread objects   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.1 Introduction

+ +

Multithreading is a paradigm that is well suited for building complex +systems such as: servers, GUIs, and high-level operating systems. +Gambit’s thread system offers mechanisms for creating threads of +execution and for synchronizing them. The thread system also supports +features which are useful in a real-time context, such as priorities, +priority inheritance and timeouts. +

+

The thread system provides the following data types: +

+ + +
+ + + + + + + + + + + +
Back: 13.1 IntroductionForward: 13.3 Mutex objects   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.2 Thread objects

+ +

A running thread is a thread that is currently executing. A +runnable thread is a thread that is ready to execute or running. +A thread is blocked if it is waiting for a mutex to become +unlocked, an I/O operation to become possible, the end of a “sleep” +period, etc. A new thread is a thread that has been allocated +but has not yet been initialized. An initialized thread is a +thread that can be made runnable. A new thread becomes runnable when +it is started by calling thread-start!. A terminated +thread is a thread that can no longer become runnable (but +deadlocked threads are not considered terminated). The only +valid transitions between the thread states are from new to +initialized, from initialized to runnable, between runnable and +blocked, and from any state except new to terminated as indicated in +the following diagram: +

+
 
                                            unblock
+                          start            <-------
+NEW -------> INITIALIZED -------> RUNNABLE -------> BLOCKED
+                       \             |      block  /
+                        \            v            /
+                         +-----> TERMINATED <----+
+
+ +

Each thread has a base priority, which is a real number (where a +higher numerical value means a higher priority), a priority boost, +which is a nonnegative real number representing the priority increase +applied to a thread when it blocks, and a quantum, which is a +nonnegative real number representing a duration in seconds. +

+

Each thread has a specific field which can be used in an +application specific way to associate data with the thread (some thread +systems call this “thread local storage”). +

+

Each thread has a mailbox which is used for inter-thread +communication. +

+
+ + + + + + + + + + + +
Back: 13.2 Thread objectsForward: 13.4 Condition variable objects   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.3 Mutex objects

+ +

A mutex can be in one of four states: locked (either owned +or not owned) and unlocked (either abandoned or +not abandoned). +

+

An attempt to lock a mutex only succeeds if the mutex is in an unlocked +state, otherwise the current thread will wait. A mutex in the +locked/owned state has an associated owner thread, which by +convention is the thread that is responsible for unlocking the mutex +(this case is typical of critical sections implemented as “lock mutex, +perform operation, unlock mutex”). A mutex in the locked/not-owned +state is not linked to a particular thread. +

+

A mutex becomes locked when a thread locks it using the +mutex-lock! primitive. A mutex becomes unlocked/abandoned when +the owner of a locked/owned mutex terminates. A mutex becomes +unlocked/not-abandoned when a thread unlocks it using the +mutex-unlock! primitive. +

+

The mutex primitives do not implement recursive mutex semantics. +An attempt to lock a mutex that is locked implies that the current +thread waits even if the mutex is owned by the current thread (this can +lead to a deadlock if no other thread unlocks the mutex). +

+

Each mutex has a specific field which can be used in an +application specific way to associate data with the mutex. +

+
+ + + + + + + + + + + +
Back: 13.3 Mutex objectsForward: 13.5 Fairness   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.4 Condition variable objects

+ +

A condition variable represents a set of blocked threads. These blocked +threads are waiting for a certain condition to become true. When a +thread modifies some program state that might make the condition true, +the thread unblocks some number of threads (one or all depending on the +primitive used) so they can check if the condition is now true. This +allows complex forms of interthread synchronization to be expressed more +conveniently than with mutexes alone. +

+

Each condition variable has a specific field which can be used in +an application specific way to associate data with the condition +variable. +

+
+ + + + + + + + + + + +
Back: 13.4 Condition variable objectsForward: 13.6 Memory coherency   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.5 Fairness

+ +

In various situations the scheduler must select one thread from a set of +threads (e.g. which thread to run when a running thread blocks or +expires its quantum, which thread to unblock when a mutex becomes +unlocked or a condition variable is signaled). The constraints on the +selection process determine the scheduler’s fairness. The +selection depends on the order in which threads become runnable or +blocked and on the priority attached to the threads. +

+

The definition of fairness requires the notion of time ordering, +i.e. “event A occured before event B”. For the purpose of +establishing time ordering, the scheduler uses a clock with a discrete, +usually variable, resolution (a “tick”). Events occuring in a given +tick can be considered to be simultaneous (i.e. if event A occured +before event B in real time, then the scheduler will claim that +event A occured before event B unless both events fall +within the same tick, in which case the scheduler arbitrarily chooses a +time ordering). +

+

Each thread T has three priorities which affect fairness; the +base priority, the boosted priority, and the effective +priority. +

+ + +

Let P(T) be the effective priority of thread T and +let R(T) be the most recent time when one of the following +events occurred for thread T, thus making it runnable: T +was started by calling thread-start!, T called +thread-yield!, T expired its quantum, or T became +unblocked. Let the relation NL(T1,T2), “T1 +no later than T2”, be true if +P(T1)<P(T2) or +P(T1)=P(T2) and +R(T1)>R(T2), and false otherwise. The +scheduler will schedule the execution of threads in such a way that +whenever there is at least one runnable thread, 1) within a finite +time at least one thread will be running, and 2) there is never a pair +of runnable threads T1 and T2 for which +NL(T1,T2) is true and T1 is not running and +T2 is running. +

+

A thread T expires its quantum when an amount of time equal to +T’s quantum has elapsed since T entered the running state +and T did not block, terminate or call thread-yield!. +At that point T exits the running state to allow other threads to +run. A thread’s quantum is thus an indication of the rate of progress +of the thread relative to the other threads of the same priority. +Moreover, the resolution of the timer measuring the running time may +cause a certain deviation from the quantum, so a thread’s quantum should +only be viewed as an approximation of the time it can run before +yielding to another thread. +

+

Threads blocked on a given mutex or condition variable will unblock in +an order which is consistent with decreasing priority and increasing +blocking time (i.e. the highest priority thread unblocks first, and +among equal priority threads the one that blocked first unblocks first). +

+
+ + + + + + + + + + + +
Back: 13.5 FairnessForward: 13.7 Timeouts   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.6 Memory coherency

+ +

Read and write operations on the store (such as reading and writing a +variable, an element of a vector or a string) are not atomic. It is +an error for a thread to write a location in the store while some +other thread reads or writes that same location. It is the +responsibility of the application to avoid write/read and write/write +races through appropriate uses of the synchronization primitives. +

+

Concurrent reads and writes to ports are allowed. It is the +responsibility of the implementation to serialize accesses to a given +port using the appropriate synchronization primitives. +

+
+ + + + + + + + + + + +
Back: 13.6 Memory coherencyForward: 13.8 Primordial thread   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.7 Timeouts

+ +

All synchronization primitives which take a timeout parameter accept +three types of values as a timeout, with the following meaning: +

+ + +

When a timeout denotes the current time or a time in the past, the +synchronization primitive claims that the timeout has been reached +only after the other synchronization conditions have been checked. +Moreover the thread remains running (it does not enter the blocked +state). For example, (mutex-lock! m 0) will lock mutex +m and return #t if m is +currently unlocked, otherwise #f is returned because the +timeout is reached. +

+
+ + + + + + + + + + + +
Back: 13.7 TimeoutsForward: 13.9 Procedures   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.8 Primordial thread

+ +

The execution of a program is initially under the control of a single +thread known as the primordial thread. The primordial thread has an +unspecified +base priority, priority boost, boosted flag, quantum, +name, specific field, dynamic environment, dynamic-wind +stack, and exception-handler. All threads are terminated when the +primordial thread terminates (normally or not). +

+
+ + + + + + + + + + + +
Back: 13.8 Primordial threadForward: 14. Dynamic environment   FastBack: 13. ThreadsUp: 13. ThreadsFastForward: 14. Dynamic environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

13.9 Procedures

+ +
(current-thread)procedure
+ +

This procedure returns the current thread. For example: +

+
 
> (current-thread)
+#<thread #1 primordial>
+> (eq? (current-thread) (current-thread))
+#t
+
+ + + +
(thread? obj)procedure
+ +

This procedure returns #t when obj is a thread object and +#f otherwise. +

+

For example: +

+
 
> (thread? (current-thread))
+#t
+> (thread? 'foo)
+#f
+
+ + + +
(make-thread thunk [name [thread-group]])procedure
+
(make-root-thread thunk [name [thread-group [input-port [output-port]]]])procedure
+ +

The make-thread procedure creates and returns an initialized +thread. This thread is not automatically made runnable (the procedure +thread-start! must be used for this). A thread has the +following fields: base priority, priority boost, boosted flag, +quantum, name, specific, end-result, end-exception, and a list of +locked/owned mutexes it owns. The thread’s execution consists of a +call to thunk with the initial continuation. This +continuation causes the (then) current thread to store the result in +its end-result field, abandon all mutexes it owns, and finally +terminate. The dynamic-wind stack of the initial continuation +is empty. The optional name is an arbitrary Scheme object which +identifies the thread (useful for debugging); it defaults to an +unspecified value. The specific field is set to an unspecified value. +The optional thread-group indicates which thread group this +thread belongs to; it defaults to the thread group of the current +thread. The base priority, priority boost, and quantum of the thread +are set to the same value as the current thread and the boosted flag +is set to false. The thread’s mailbox is initially empty. The thread +inherits the dynamic environment from the current thread. Moreover, in +this dynamic environment the exception-handler is bound to the +initial exception-handler which is a unary procedure which +causes the (then) current thread to store in its end-exception field +an uncaught-exception object whose “reason” is the argument of the +handler, abandon all mutexes it owns, and finally terminate. +

+

The make-root-thread procedure behaves like the +make-thread procedure except the created thread does not +inherit the dynamic environment from the current thread and the base +priority is set to 0, the priority boost is set to 1.0e-6, and the +quantum is set to 0.02. The dynamic environment of the thread has the +global bindings of the parameter objects, except +current-input-port which is bound to input-port, +current-output-port which is bound to output-port, and +current-directory which is bound to the initial current working +directory of the current process. If input-port is not +specified it defaults to a port corresponding to the standard input +(stdin). If output-port is not specified it defaults to +a port corresponding to the standard output (stdout). +

+

For example: +

+
 
> (make-thread (lambda () (write 'hello)))
+#<thread #2>
+> (make-root-thread (lambda () (write 'world)) 'a-name)
+#<thread #3 a-name>
+
+ + + +
(thread-name thread)procedure
+ +

This procedure returns the name of the thread. For example: +

+
 
> (thread-name (make-thread (lambda () #f) 'foo))
+foo
+
+ + + +
(thread-specific thread)procedure
+
(thread-specific-set! thread obj)procedure
+ +

The thread-specific procedure returns the content of the +thread’s specific field. +

+

The thread-specific-set! procedure stores obj into the +thread’s specific field and returns an unspecified value. +

+

For example: +

+
 
> (thread-specific-set! (current-thread) "hello")
+> (thread-specific (current-thread))
+"hello"
+
+ + + +
(thread-base-priority thread)procedure
+
(thread-base-priority-set! thread priority)procedure
+ +

The procedure thread-base-priority returns a real number which +corresponds to the base priority of the thread. +

+

The procedure thread-base-priority-set! changes the base +priority of the thread to priority and returns an +unspecified value. The priority must be a real number. +

+

For example: +

+
 
> (thread-base-priority-set! (current-thread) 12.3)
+> (thread-base-priority (current-thread))
+12.3
+
+ + + +
(thread-priority-boost thread)procedure
+
(thread-priority-boost-set! thread priority-boost)procedure
+ +

The procedure thread-priority-boost returns a real number which +corresponds to the priority boost of the thread. +

+

The procedure thread-priority-boost-set! changes the priority +boost of the thread to priority-boost and returns an +unspecified value. The priority-boost must be a nonnegative +real. +

+

For example: +

+
 
> (thread-priority-boost-set! (current-thread) 2.5)
+> (thread-priority-boost (current-thread))
+2.5
+
+ + + +
(thread-quantum thread)procedure
+
(thread-quantum-set! thread quantum)procedure
+ +

The procedure thread-quantum returns a real number which +corresponds to the quantum of the thread. +

+

The procedure thread-quantum-set! changes the quantum of the +thread to quantum and returns an unspecified value. The +quantum must be a nonnegative real. A value of zero selects the +smallest quantum supported by the implementation. +

+

For example: +

+
 
> (thread-quantum-set! (current-thread) 1.5)
+> (thread-quantum (current-thread))
+1.5
+> (thread-quantum-set! (current-thread) 0)
+> (thread-quantum (current-thread))
+0.
+
+ + + +
(thread-start! thread)procedure
+ +

This procedure makes thread runnable and returns the +thread. The thread must be an initialized thread. +

+

For example: +

+
 
> (let ((t (thread-start! (make-thread (lambda () (write 'a))))))
+    (write 'b)
+    (thread-join! t))
+ab> or ba>
+
+ +

NOTE: It is useful to separate thread creation and thread activation +to avoid the race condition that would occur if the created thread +tries to examine a table in which the current thread stores the +created thread. See the last example of the thread-terminate! +procedure which contains mutually recursive threads. +

+ + +
(thread-yield!)procedure
+ +

This procedure causes the current thread to exit the running state as +if its quantum had expired and returns an unspecified value. +

+

For example: +

+
 
; a busy loop that avoids being too wasteful of the CPU
+
+(let loop ()
+  (if (mutex-lock! m 0) ; try to lock m but don't block
+      (begin
+        (display "locked mutex m")
+        (mutex-unlock! m))
+      (begin
+        (do-something-else)
+        (thread-yield!) ; relinquish rest of quantum
+        (loop))))
+
+ + + +
(thread-sleep! timeout)procedure
+ +

This procedure causes the current thread to wait until the timeout is +reached and returns an unspecified value. This blocks the thread only +if timeout represents a point in the future. It is an error for +timeout to be #f. +

+

For example: +

+
 
; a clock with a gradual drift:
+
+(let loop ((x 1))
+  (thread-sleep! 1)
+  (write x)
+  (loop (+ x 1)))
+
+; a clock with no drift:
+
+(let ((start (time->seconds (current-time)))
+  (let loop ((x 1))
+    (thread-sleep! (seconds->time (+ x start)))
+    (write x)
+    (loop (+ x 1))))
+
+ + + +
(thread-terminate! thread)procedure
+ +

This procedure causes an abnormal termination of the thread. If +the thread is not already terminated, all mutexes owned by the +thread become unlocked/abandoned and a +terminated-thread-exception object is stored in the thread’s +end-exception field. If thread is the current thread, +thread-terminate! does not return. Otherwise +thread-terminate! returns an unspecified value; the termination +of the thread will occur at some point between the calling of +thread-terminate! and a finite time in the future (an explicit +thread synchronization is needed to detect termination, see +thread-join!). +

+

For example: +

+
 
(define (amb thunk1 thunk2)
+  (let ((result #f)
+        (result-mutex (make-mutex))
+        (done-mutex (make-mutex)))
+    (letrec ((child1
+              (make-thread
+                (lambda ()
+                  (let ((x (thunk1)))
+                    (mutex-lock! result-mutex #f #f)
+                    (set! result x)
+                    (thread-terminate! child2)
+                    (mutex-unlock! done-mutex)))))
+             (child2
+              (make-thread
+                (lambda ()
+                  (let ((x (thunk2)))
+                    (mutex-lock! result-mutex #f #f)
+                    (set! result x)
+                    (thread-terminate! child1)
+                    (mutex-unlock! done-mutex))))))
+      (mutex-lock! done-mutex #f #f)
+      (thread-start! child1)
+      (thread-start! child2)
+      (mutex-lock! done-mutex #f #f)
+      result)))
+
+ +

NOTE: This operation must be used carefully because it terminates a +thread abruptly and it is impossible for that thread to perform any +kind of cleanup. This may be a problem if the thread is in the middle +of a critical section where some structure has been put in an +inconsistent state. However, another thread attempting to enter this +critical section will raise an abandoned-mutex-exception object +because the mutex is unlocked/abandoned. This helps avoid observing +an inconsistent state. Clean termination can be obtained by polling, +as shown in the example below. +

+

For example: +

+
 
(define (spawn thunk)
+  (let ((t (make-thread thunk)))
+    (thread-specific-set! t #t)
+    (thread-start! t)
+    t))
+
+(define (stop! thread)
+  (thread-specific-set! thread #f)
+  (thread-join! thread))
+
+(define (keep-going?)
+  (thread-specific (current-thread)))
+
+(define count!
+  (let ((m (make-mutex))
+        (i 0))
+    (lambda ()
+      (mutex-lock! m)
+      (let ((x (+ i 1)))
+        (set! i x)
+        (mutex-unlock! m)
+        x))))
+
+(define (increment-forever!)
+  (let loop () (count!) (if (keep-going?) (loop))))
+
+(let ((t1 (spawn increment-forever!))
+      (t2 (spawn increment-forever!)))
+  (thread-sleep! 1)
+  (stop! t1)
+  (stop! t2)
+  (count!))  ==>  377290
+
+ + + +
(thread-join! thread [timeout [timeout-val]])procedure
+ +

This procedure causes the current thread to wait until the +thread terminates (normally or not) or until the timeout is +reached if timeout is supplied. If the timeout is reached, +thread-join! returns timeout-val if it is supplied, +otherwise a join-timeout-exception object is raised. If the +thread terminated normally, the content of the end-result field +is returned, otherwise the content of the end-exception field is +raised. +

+

For example: +

+
 
(let ((t (thread-start! (make-thread (lambda () (expt 2 100))))))
+  (do-something-else)
+  (thread-join! t))  ==>  1267650600228229401496703205376
+
+(let ((t (thread-start! (make-thread (lambda () (raise 123))))))
+  (do-something-else)
+  (with-exception-handler
+    (lambda (exc)
+      (if (uncaught-exception? exc)
+          (* 10 (uncaught-exception-reason exc))
+          99999))
+    (lambda ()
+      (+ 1 (thread-join! t)))))  ==>  1231
+
+(define thread-alive?
+  (let ((unique (list 'unique)))
+    (lambda (thread)
+      ; Note: this procedure raises an exception if
+      ; the thread terminated abnormally.
+      (eq? (thread-join! thread 0 unique) unique))))
+
+(define (wait-for-termination! thread)
+  (let ((eh (current-exception-handler)))
+    (with-exception-handler
+      (lambda (exc)
+        (if (not (or (terminated-thread-exception? exc)
+                     (uncaught-exception? exc)))
+            (eh exc))) ; unexpected exceptions are handled by eh
+      (lambda ()
+        ; The following call to thread-join! will wait until the
+        ; thread terminates.  If the thread terminated normally
+        ; thread-join! will return normally.  If the thread
+        ; terminated abnormally then one of these two exception
+        ; objects is raised by thread-join!:
+        ;   - terminated-thread-exception object
+        ;   - uncaught-exception object
+        (thread-join! thread)
+        #f)))) ; ignore result of thread-join!
+
+ + + +
(thread-send thread msg)procedure
+ +

Each thread has a mailbox which stores messages delivered to the +thread in the order delivered. +

+

The procedure thread-send adds the message msg at the end +of the mailbox of thread thread and returns an unspecified +value. +

+

For example: +

+
 
> (thread-send (current-thread) 111)
+> (thread-send (current-thread) 222)
+> (thread-receive)
+111
+> (thread-receive)
+222
+
+ + + +
(thread-receive [timeout [default]])procedure
+
(thread-mailbox-next [timeout [default]])procedure
+
(thread-mailbox-rewind)procedure
+
(thread-mailbox-extract-and-rewind)procedure
+ +

To allow a thread to examine the messages in its mailbox without +removing them from the mailbox, each thread has a mailbox cursor +which normally points to the last message accessed in the mailbox. +When a mailbox cursor is rewound using the procedure +thread-mailbox-rewind or +thread-mailbox-extract-and-rewind or thread-receive, the +cursor does not point to a message, but the next call to +thread-receive and thread-mailbox-next will set the +cursor to the oldest message in the mailbox. +

+

The procedure thread-receive advances the mailbox cursor of the +current thread to the next message, removes that message from the +mailbox, rewinds the mailbox cursor, and returns the message. When +timeout is not specified, the current thread will wait until a +message is available in the mailbox. When timeout is specified +and default is not specified, a +mailbox-receive-timeout-exception object is raised if the timeout is +reached before a message is available. When timeout is +specified and default is specified, default is returned if +the timeout is reached before a message is available. +

+

The procedure thread-mailbox-next behaves like +thread-receive except that the message remains in the mailbox +and the mailbox cursor is not rewound. +

+

The procedures thread-mailbox-rewind or +thread-mailbox-extract-and-rewind rewind the mailbox cursor of +the current thread so that the next call to thread-mailbox-next +and thread-receive will access the oldest message in the +mailbox. Additionally the procedure +thread-mailbox-extract-and-rewind will remove from the mailbox +the message most recently accessed by a call to +thread-mailbox-next. When thread-mailbox-next has not +been called since the last call to thread-receive or +thread-mailbox-rewind or +thread-mailbox-extract-and-rewind, a call to +thread-mailbox-extract-and-rewind only resets the mailbox +cursor (no message is removed). +

+

For example: +

+
 
> (thread-send (current-thread) 111)
+> (thread-receive 1 999)
+111
+> (thread-send (current-thread) 222)
+> (thread-send (current-thread) 333)
+> (thread-mailbox-next 1 999)
+222
+> (thread-mailbox-next 1 999)
+333
+> (thread-mailbox-next 1 999)
+999
+> (thread-mailbox-extract-and-rewind)
+> (thread-receive 1 999)
+222
+> (thread-receive 1 999)
+999
+
+ + + +
(mailbox-receive-timeout-exception? obj)procedure
+
(mailbox-receive-timeout-exception-procedure exc)procedure
+
(mailbox-receive-timeout-exception-arguments exc)procedure
+ +

Mailbox-receive-timeout-exception objects are raised by the procedures +thread-receive and thread-mailbox-next when a timeout +expires before a message is available and no default value is +specified. The parameter exc must be a +mailbox-receive-timeout-exception object. +

+

The procedure mailbox-receive-timeout-exception? returns +#t when obj is a mailbox-receive-timeout-exception +object and #f otherwise. +

+

The procedure mailbox-receive-timeout-exception-procedure +returns the procedure that raised exc. +

+

The procedure mailbox-receive-timeout-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (mailbox-receive-timeout-exception? exc)
+        (list (mailbox-receive-timeout-exception-procedure exc)
+              (mailbox-receive-timeout-exception-arguments exc))
+        'not-mailbox-receive-timeout-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (thread-receive 1)))
+(#<procedure #2 thread-receive> (1))
+
+ + + +
(mutex? obj)procedure
+ +

This procedure returns #t when obj is a mutex object and +#f otherwise. +

+

For example: +

+
 
> (mutex? (make-mutex))
+#t
+> (mutex? 'foo)
+#f
+
+ + + +
(make-mutex [name])procedure
+ +

This procedure returns a new mutex in the unlocked/not-abandoned +state. The optional name is an arbitrary Scheme object which +identifies the mutex (useful for debugging); it defaults to an +unspecified value. The mutex’s specific field is set to an +unspecified value. +

+

For example: +

+
 
> (make-mutex)
+#<mutex #2>
+> (make-mutex 'foo)
+#<mutex #3 foo>
+
+ + + +
(mutex-name mutex)procedure
+ +

Returns the name of the mutex. For example: +

+
 
> (mutex-name (make-mutex 'foo))
+foo
+
+ + + +
(mutex-specific mutex)procedure
+
(mutex-specific-set! mutex obj)procedure
+ +

The mutex-specific procedure returns the content of the +mutex’s specific field. +

+

The mutex-specific-set! procedure stores obj into the +mutex’s specific field and returns an unspecified value. +

+

For example: +

+
 
> (define m (make-mutex))
+> (mutex-specific-set! m "hello")
+> (mutex-specific m)
+"hello"
+> (define (mutex-lock-recursively! mutex)
+    (if (eq? (mutex-state mutex) (current-thread))
+        (let ((n (mutex-specific mutex)))
+          (mutex-specific-set! mutex (+ n 1)))
+        (begin
+          (mutex-lock! mutex)
+          (mutex-specific-set! mutex 0))))
+> (define (mutex-unlock-recursively! mutex)
+    (let ((n (mutex-specific mutex)))
+      (if (= n 0)
+          (mutex-unlock! mutex)
+          (mutex-specific-set! mutex (- n 1)))))
+> (mutex-lock-recursively! m)
+> (mutex-lock-recursively! m)
+> (mutex-lock-recursively! m)
+> (mutex-specific m)
+2
+
+ + + +
(mutex-state mutex)procedure
+ +

Thos procedure returns information about the state of the mutex. +The possible results are: +

+ + +

For example: +

+
 
(mutex-state (make-mutex))  ==>  not-abandoned
+
+(define (thread-alive? thread)
+  (let ((mutex (make-mutex)))
+    (mutex-lock! mutex #f thread)
+    (let ((state (mutex-state mutex)))
+      (mutex-unlock! mutex) ; avoid space leak
+      (eq? state thread))))
+
+ + + +
(mutex-lock! mutex [timeout [thread]])procedure
+ +

This procedure locks mutex. If the mutex is currently +locked, the current thread waits until the mutex is unlocked, or +until the timeout is reached if timeout is supplied. If the +timeout is reached, mutex-lock! returns #f. Otherwise, +the state of the mutex is changed as follows: +

+ + +

After changing the state of the mutex, an +abandoned-mutex-exception object is raised if the mutex was +unlocked/abandoned before the state change, otherwise +mutex-lock! returns #t. It is not an error if the +mutex is owned by the current thread (but the current thread +will have to wait). +

+

For example: +

+
 
; an implementation of a mailbox object of depth one; this
+; implementation does not behave well in the presence of forced
+; thread terminations using thread-terminate! (deadlock can occur
+; if a thread is terminated in the middle of a put! or get! operation)
+
+(define (make-empty-mailbox)
+  (let ((put-mutex (make-mutex)) ; allow put! operation
+        (get-mutex (make-mutex))
+        (cell #f))
+
+    (define (put! obj)
+      (mutex-lock! put-mutex #f #f) ; prevent put! operation
+      (set! cell obj)
+      (mutex-unlock! get-mutex)) ; allow get! operation
+
+    (define (get!)
+      (mutex-lock! get-mutex #f #f) ; wait until object in mailbox
+      (let ((result cell))
+        (set! cell #f) ; prevent space leaks
+        (mutex-unlock! put-mutex) ; allow put! operation
+        result))
+
+    (mutex-lock! get-mutex #f #f) ; prevent get! operation
+
+    (lambda (msg)
+      (case msg
+        ((put!) put!)
+        ((get!) get!)
+        (else (error "unknown message"))))))
+
+(define (mailbox-put! m obj) ((m 'put!) obj))
+(define (mailbox-get! m) ((m 'get!)))
+
+; an alternate implementation of thread-sleep!
+
+(define (sleep! timeout)
+  (let ((m (make-mutex)))
+    (mutex-lock! m #f #f)
+    (mutex-lock! m timeout #f)))
+
+; a procedure that waits for one of two mutexes to unlock
+
+(define (lock-one-of! mutex1 mutex2)
+  ; this procedure assumes that neither mutex1 or mutex2
+  ; are owned by the current thread
+  (let ((ct (current-thread))
+        (done-mutex (make-mutex)))
+    (mutex-lock! done-mutex #f #f)
+    (let ((t1 (thread-start!
+               (make-thread
+                (lambda ()
+                  (mutex-lock! mutex1 #f ct)
+                  (mutex-unlock! done-mutex)))))
+          (t2 (thread-start!
+               (make-thread
+                (lambda ()
+                  (mutex-lock! mutex2 #f ct)
+                  (mutex-unlock! done-mutex))))))
+      (mutex-lock! done-mutex #f #f)
+      (thread-terminate! t1)
+      (thread-terminate! t2)
+      (if (eq? (mutex-state mutex1) ct)
+          (begin
+            (if (eq? (mutex-state mutex2) ct)
+                (mutex-unlock! mutex2)) ; don't lock both
+            mutex1)
+          mutex2))))
+
+ + + +
(mutex-unlock! mutex [condition-variable [timeout]])procedure
+ +

This procedure unlocks the mutex by making it +unlocked/not-abandoned. It is not an error to unlock an unlocked +mutex and a mutex that is owned by any thread. If +condition-variable is supplied, the current thread is blocked +and added to the condition-variable before unlocking +mutex; the thread can unblock at any time but no later than when +an appropriate call to condition-variable-signal! or +condition-variable-broadcast! is performed (see below), and no +later than the timeout (if timeout is supplied). If there are +threads waiting to lock this mutex, the scheduler selects a +thread, the mutex becomes locked/owned or locked/not-owned, and the +thread is unblocked. mutex-unlock! returns #f when the +timeout is reached, otherwise it returns #t. +

+

NOTE: The reason the thread can unblock at any time (when +condition-variable is supplied) is that the scheduler, when it +detects a serious problem such as a deadlock, must interrupt one of +the blocked threads (such as the primordial thread) so that it can +perform some appropriate action. After a thread blocked on a +condition-variable has handled such an interrupt it would be wrong for +the scheduler to return the thread to the blocked state, because any +calls to condition-variable-broadcast! during the interrupt +will have gone unnoticed. It is necessary for the thread to remain +runnable and return from the call to mutex-unlock! with a +result of #t. +

+

NOTE: mutex-unlock! is related to the “wait” operation on +condition variables available in other thread systems. The main +difference is that “wait” automatically locks mutex just +after the thread is unblocked. This operation is not performed by +mutex-unlock! and so must be done by an explicit call to +mutex-lock!. This has the advantages that a different timeout +and exception-handler can be specified on the mutex-lock! and +mutex-unlock! and the location of all the mutex operations is +clearly apparent. +

+

For example: +

+
 
(let loop ()
+  (mutex-lock! m)
+  (if (condition-is-true?)
+      (begin
+        (do-something-when-condition-is-true)
+        (mutex-unlock! m))
+      (begin
+        (mutex-unlock! m cv)
+        (loop))))
+
+ + + +
(condition-variable? obj)procedure
+ +

This procedure returns #t when obj is a +condition-variable object and #f otherwise. +

+

For example: +

+
 
> (condition-variable? (make-condition-variable))
+#t
+> (condition-variable? 'foo)
+#f
+
+ + + +
(make-condition-variable [name])procedure
+ +

This procedure returns a new empty condition variable. The optional +name is an arbitrary Scheme object which identifies the +condition variable (useful for debugging); it defaults to an +unspecified value. The condition variable’s specific field is set to +an unspecified value. +

+

For example: +

+
 
> (make-condition-variable)
+#<condition-variable #2>
+
+ + + +
(condition-variable-name condition-variable)procedure
+ +

This procedure returns the name of the condition-variable. For +example: +

+
 
> (condition-variable-name (make-condition-variable 'foo))
+foo
+
+ + + +
(condition-variable-specific condition-variable)procedure
+
(condition-variable-specific-set! condition-variable obj)procedure
+ +

The condition-variable-specific procedure returns the content +of the condition-variable’s specific field. +

+

The condition-variable-specific-set! procedure stores obj +into the condition-variable’s specific field and returns +an unspecified value. +

+

For example: +

+
 
> (define cv (make-condition-variable))
+> (condition-variable-specific-set! cv "hello")
+> (condition-variable-specific cv)
+"hello"
+
+ + + +
(condition-variable-signal! condition-variable)procedure
+ +

This procedure unblocks a thread blocked on the +condition-variable (if there is at least one) and returns an +unspecified value. +

+

For example: +

+
 
; an implementation of a mailbox object of depth one; this
+; implementation behaves gracefully when threads are forcibly
+; terminated using thread-terminate! (an abandoned-mutex-exception
+; object will be raised when a put! or get! operation is attempted
+; after a thread is terminated in the middle of a put! or get!
+; operation)
+
+(define (make-empty-mailbox)
+  (let ((mutex (make-mutex))
+        (put-condvar (make-condition-variable))
+        (get-condvar (make-condition-variable))
+        (full? #f)
+        (cell #f))
+
+    (define (put! obj)
+      (mutex-lock! mutex)
+      (if full?
+          (begin
+            (mutex-unlock! mutex put-condvar)
+            (put! obj))
+          (begin
+            (set! cell obj)
+            (set! full? #t)
+            (condition-variable-signal! get-condvar)
+            (mutex-unlock! mutex))))
+
+    (define (get!)
+      (mutex-lock! mutex)
+      (if (not full?)
+          (begin
+            (mutex-unlock! mutex get-condvar)
+            (get!))
+          (let ((result cell))
+            (set! cell #f) ; avoid space leaks
+            (set! full? #f)
+            (condition-variable-signal! put-condvar)
+            (mutex-unlock! mutex)
+            result)))
+
+    (lambda (msg)
+      (case msg
+        ((put!) put!)
+        ((get!) get!)
+        (else (error "unknown message"))))))
+
+(define (mailbox-put! m obj) ((m 'put!) obj))
+(define (mailbox-get! m) ((m 'get!)))
+
+ + + +
(condition-variable-broadcast! condition-variable)procedure
+ +

This procedure unblocks all the thread blocked on the +condition-variable and returns an unspecified value. +

+

For example: +

+
 
(define (make-semaphore n)
+  (vector n (make-mutex) (make-condition-variable)))
+
+(define (semaphore-wait! sema)
+  (mutex-lock! (vector-ref sema 1))
+  (let ((n (vector-ref sema 0)))
+    (if (> n 0)
+        (begin
+          (vector-set! sema 0 (- n 1))
+          (mutex-unlock! (vector-ref sema 1)))
+        (begin
+          (mutex-unlock! (vector-ref sema 1) (vector-ref sema 2))
+          (semaphore-wait! sema))))
+
+(define (semaphore-signal-by! sema increment)
+  (mutex-lock! (vector-ref sema 1))
+  (let ((n (+ (vector-ref sema 0) increment)))
+    (vector-set! sema 0 n)
+    (if (> n 0)
+        (condition-variable-broadcast! (vector-ref sema 2)))
+    (mutex-unlock! (vector-ref sema 1))))
+
+ + + +
+ + + + + + + + + + + +
Back: 13.9 ProceduresForward: 15. Exceptions   FastBack: 13. ThreadsUp: Gambit-CFastForward: 15. ExceptionsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

14. Dynamic environment

+ +

The dynamic environment is the structure which allows the system +to find the value returned by the standard procedures +current-input-port and current-output-port. The +standard procedures with-input-from-file and +with-output-to-file extend the dynamic environment to produce a +new dynamic environment which is in effect for the dynamic extent of +the call to the thunk passed as their last argument. These procedures +are essentially special purpose dynamic binding operations on hidden +dynamic variables (one for current-input-port and one for +current-output-port). Gambit generalizes this dynamic binding +mechanism to allow the user to introduce new dynamic variables, called +parameter objects, and dynamically bind them. The parameter +objects implemented by Gambit are compatible with the specification of +the “Parameter objects SRFI” (SRFI 39). +

+

One important issue is the relationship between the dynamic +environments of the parent and child threads when a thread is created. +Each thread has its own dynamic environment that is accessed when +looking up the value bound to a parameter object by that thread. When +a thread’s dynamic environment is extended it does not affect the +dynamic environment of other threads. When a thread is created it is +given a dynamic environment whose bindings are inherited from the +parent thread. In this inherited dynamic environment the parameter +objects are bound to the same cells as the parent’s dynamic +environment (in other words an assignment of a new value to a +parameter object is visible in the other thread). +

+

Another important issue is the interaction between the +dynamic-wind procedure and dynamic environments. When a thread +creates a continuation, the thread’s dynamic environment and the +dynamic-wind stack are saved within the continuation (an +alternate but equivalent point of view is that the dynamic-wind +stack is part of the dynamic environment). When this continuation is +invoked the required dynamic-wind before and after thunks are +called and the saved dynamic environment is reinstated as the dynamic +environment of the current thread. During the call to each required +dynamic-wind before and after thunk, the dynamic environment +and the dynamic-wind stack in effect when the corresponding +dynamic-wind was executed are reinstated. Note that this +specification precisely defines the semantics of calling +call-with-current-continuation or invoking a continuation +within a before or after thunk. The semantics are well defined even +when a continuation created by another thread is invoked. Below is an +example exercising the subtleties of this semantics. +

+
 
(with-output-to-file
+ "foo"
+ (lambda ()
+   (let ((k (call-with-current-continuation
+             (lambda (exit)
+               (with-output-to-file
+                "bar"
+                (lambda ()
+                  (dynamic-wind
+                   (lambda ()
+                     (write '(b1))
+                     (force-output))
+                   (lambda ()
+                     (let ((x (call-with-current-continuation
+                               (lambda (cont) (exit cont)))))
+                       (write '(t1))
+                       (force-output)
+                       x))
+                   (lambda ()
+                     (write '(a1))
+                     (force-output)))))))))
+     (if k
+         (dynamic-wind
+          (lambda ()
+            (write '(b2))
+            (force-output))
+          (lambda ()
+            (with-output-to-file
+             "baz"
+             (lambda ()
+               (write '(t2))
+               (force-output)
+               ; go back inside (with-output-to-file "bar" ...)
+               (k #f))))
+          (lambda ()
+            (write '(a2))
+            (force-output)))))))
+
+ +

The following actions will occur when this code is executed: +(b1)(a1) is written to “bar”, (b2) is then written to +“foo”, (t2) is then written to “baz”, (a2) is then +written to “foo”, and finally (b1)(t1)(a1) is written to +“bar”. +

+
(make-parameter obj [filter])procedure
+ +

The dynamic environment is composed of two parts: the local +dynamic environment and the global dynamic environment. There +is a single global dynamic environment, and it is used to lookup +parameter objects that can’t be found in the local dynamic +environment. +

+

The make-parameter procedure returns a new parameter +object. The filter argument is a one argument conversion +procedure. If it is not specified, filter defaults to the +identity function. +

+

The global dynamic environment is updated to associate the parameter +object to a new cell. The initial content of the cell is the result +of applying the conversion procedure to obj. +

+

A parameter object is a procedure which accepts zero or one argument. +The cell bound to a particular parameter object in the dynamic +environment is accessed by calling the parameter object. When no +argument is passed, the content of the cell is returned. When one +argument is passed the content of the cell is updated with the result +of applying the parameter object’s conversion procedure to the +argument. Note that the conversion procedure can be used for +guaranteeing the type of the parameter object’s binding and/or to +perform some conversion of the value. +

+

For example: +

+
 
> (define radix (make-parameter 10))
+> (radix)
+10
+> (radix 2)
+> (radix)
+2
+> (define prompt
+    (make-parameter
+      123
+      (lambda (x)
+        (if (string? x)
+            x
+            (object->string x)))))
+> (prompt)
+"123"
+> (prompt "$")
+> (prompt)
+"$"
+> (define write-shared
+    (make-parameter
+      #f
+      (lambda (x)
+        (if (boolean? x)
+            x
+            (error "only booleans are accepted by write-shared")))))
+> (write-shared 123)
+*** ERROR IN ##make-parameter -- only booleans are accepted by write-shared
+
+ + + +
(parameterize ((procedure value)…) body)special form
+ +

The parameterize form, evaluates all procedure and +value expressions in an unspecified order. All the +procedure expressions must evaluate to procedures, either parameter +objects or procedures accepting zero and one argument. Then, +for each procedure p and in an unspecified order: +

+ + +

The result(s) of the parameterize form are the result(s) of the +body. +

+

Note that using procedures instead of parameter objects may lead to +unexpected results in multithreaded programs because the before and +after thunks of the dynamic-wind are not called when control +switches between threads. +

+

For example: +

+
 
> (define radix (make-parameter 2))
+> (define prompt
+    (make-parameter
+      123
+      (lambda (x)
+        (if (string? x)
+            x
+            (object->string x)))))
+> (radix)
+2
+> (parameterize ((radix 16)) (radix))
+16
+> (radix)
+2
+> (define (f n) (number->string n (radix)))
+> (f 10)
+"1010"
+> (parameterize ((radix 8)) (f 10))
+"12"
+> (parameterize ((radix 8) (prompt (f 10))) (prompt))
+"1010"
+> (define p
+    (let ((x 1))
+      (lambda args
+        (if (null? args) x (set! x (car args))))))
+> (let* ((a (p))
+         (b (parameterize ((p 2)) (list (p))))
+         (c (p)))
+    (list a b c))
+(1 (2) 1)
+
+ + + +
+ + + + + + + + + + + +
Back: 14. Dynamic environmentForward: 15.1 Exception-handling   FastBack: 14. Dynamic environmentUp: Gambit-CFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15. Exceptions

+ + + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 15. ExceptionsForward: 15.2 Exception objects related to memory management   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.1 Exception-handling

+ +

Gambit’s exception-handling model is inspired from the withdrawn +“Exception Handling SRFI” (SRFI 12), the “Multithreading support +SRFI” (SRFI 18), and the “Exception Handling for Programs SRFI” +(SRFI 34). The two fundamental operations are the dynamic binding of +an exception handler (i.e. the procedure +with-exception-handler) and the invocation of the exception +handler (i.e. the procedure raise). +

+

All predefined procedures which check for errors (including type +errors, memory allocation errors, host operating-system errors, etc) +report these errors using the exception-handling system (i.e. they +“raise” an exception that can be handled in a user-defined exception +handler). When an exception is raised and the exception is not +handled by a user-defined exception handler, the predefined exception +handler will display an error message (if the primordial thread raised +the exception) or the thread will silently terminate with no error +message (if it is not the primordial thread that raised the +exception). This default behavior can be changed through the +-:d runtime option (see section Runtime options). +

+

Predefined procedures normally raise exceptions by performing a +tail-call to the exception handler (the exceptions are “complex” +procedures such as eval, compile-file, read, +write, etc). This means that the continuation of the exception +handler and of the REPL that may be started due to this is normally +the continuation of the predefined procedure that raised the +exception. By exiting the REPL with the ,(c expression) +command it is thus possible to resume the program as though the call +to the predefined procedure returned the value of expression. +For example: +

+
 
> (define (f x) (+ (car x) 1))
+> (f 2) ; typo... we meant to say (f '(2))
+*** ERROR IN f, (console)@1.18 -- (Argument 1) PAIR expected
+(car 2)
+1> ,(c 2)
+3
+
+ +
(current-exception-handler [new-exception-handler])procedure
+ + +

The parameter object current-exception-handler is bound to the +current exception-handler. Calling this procedure with no argument +returns the current exception-handler and calling this procedure with +one argument sets the current exception-handler to +new-exception-handler. +

+

For example: +

+
 
> (current-exception-handler)
+#<procedure #2 primordial-exception-handler>
+> (current-exception-handler (lambda (exc) (pp exc) 999))
+> (/ 1 0)
+#<divide-by-zero-exception #3>
+999
+
+ + + +
(with-exception-handler handler thunk)procedure
+ +

Returns the result(s) of calling thunk with no arguments. The +handler, which must be a procedure, is installed as the current +exception-handler in the dynamic environment in effect during the call +to thunk. Note that the dynamic environment in effect during +the call to handler has handler as the exception-handler. +Consequently, an exception raised during the call to handler may +lead to an infinite loop. +

+

For example: +

+
 
> (with-exception-handler
+    (lambda (e) (write e) 5)
+    (lambda () (+ 1 (* 2 3) 4)))
+11
+> (with-exception-handler
+    (lambda (e) (write e) 5)
+    (lambda () (+ 1 (* 'foo 3) 4)))
+#<type-exception #2>10
+> (with-exception-handler
+    (lambda (e) (write e 9))
+    (lambda () (+ 1 (* 'foo 3) 4)))
+infinite loop
+
+ + + +
(with-exception-catcher handler thunk)procedure
+ +

Returns the result(s) of calling thunk with no arguments. A new +exception-handler is installed as the current exception-handler in the +dynamic environment in effect during the call to thunk. This +new exception-handler will call the handler, which must be a +procedure, with the exception object as an argument and with the same +continuation as the call to with-exception-catcher. This +implies that the dynamic environment in effect during the call to +handler is the same as the one in effect at the call to +with-exception-catcher. Consequently, an exception raised +during the call to handler will not lead to an infinite loop. +

+

For example: +

+
 
> (with-exception-catcher
+    (lambda (e) (write e) 5)
+    (lambda () (+ 1 (* 2 3) 4)))
+11
+> (with-exception-catcher
+    (lambda (e) (write e) 5)
+    (lambda () (+ 1 (* 'foo 3) 4)))
+#<type-exception #2>5
+> (with-exception-catcher
+    (lambda (e) (write e 9))
+    (lambda () (+ 1 (* 'foo 3) 4)))
+*** ERROR IN (console)@7.1 -- (Argument 2) OUTPUT PORT expected
+(write '#<type-exception #3> 9)
+
+ + + +
(raise obj)procedure
+ +

This procedure tail-calls the current exception-handler with obj +as the sole argument. If the exception-handler returns, the +continuation of the call to raise is invoked. +

+

For example: +

+
 
> (with-exception-handler
+    (lambda (exc)
+      (pp exc)
+      100)
+    (lambda ()
+      (+ 1 (raise "hello"))))
+"hello"
+101
+
+ + + +
(abort obj)procedure
+
(noncontinuable-exception? obj)procedure
+
(noncontinuable-exception-reason exc)procedure
+ +

The procedure abort calls the current exception-handler with +obj as the sole argument. If the exception-handler returns, the +procedure abort will be tail-called with a +noncontinuable-exception object, whose reason field is obj, as +sole argument. +

+

Noncontinuable-exception objects are raised by the abort +procedure when the exception-handler returns. The parameter exc +must be a noncontinuable-exception object. +

+

The procedure noncontinuable-exception? returns +#t when obj is a noncontinuable-exception +object and #f otherwise. +

+

The procedure noncontinuable-exception-reason returns the +argument of the call to abort that raised exc. +

+

For example: +

+
 
> (call-with-current-continuation
+    (lambda (k)
+      (with-exception-handler
+        (lambda (exc)
+          (pp exc)
+          (if (noncontinuable-exception? exc)
+              (k (list (noncontinuable-exception-reason exc)))
+              100))
+        (lambda ()
+          (+ 1 (abort "hello"))))))
+"hello"
+#<noncontinuable-exception #2>
+("hello")
+
+ + + +
+ + + + + + + + + + + +
Back: 15.1 Exception-handlingForward: 15.3 Exception objects related to the host environment   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.2 Exception objects related to memory management

+ +
(heap-overflow-exception? obj)procedure
+ +

Heap-overflow-exception objects are raised when the allocation of an +object would cause the heap to use more memory space than is available. +

+

The procedure heap-overflow-exception? returns +#t when obj is a heap-overflow-exception +object and #f otherwise. +

+

For example: +

+
 
> (define (handler exc)
+    (if (heap-overflow-exception? exc)
+        exc
+        'not-heap-overflow-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (define (f x) (f (cons 1 x)))
+      (f '())))
+#<heap-overflow-exception #2>
+
+ + + +
(stack-overflow-exception? obj)procedure
+ +

Stack-overflow-exception objects are raised when the allocation of a +continuation frame would cause the heap to use more memory space than +is available. +

+

The procedure stack-overflow-exception? returns +#t when obj is a stack-overflow-exception +object and #f otherwise. +

+

For example: +

+
 
> (define (handler exc)
+    (if (stack-overflow-exception? exc)
+        exc
+        'not-stack-overflow-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (define (f) (+ 1 (f)))
+      (f)))
+#<stack-overflow-exception #2>
+
+ + + +
+ + + + + + + + + + + +
Back: 15.2 Exception objects related to memory managementForward: 15.4 Exception objects related to threads   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.3 Exception objects related to the host environment

+ +
(os-exception? obj)procedure
+
(os-exception-procedure exc)procedure
+
(os-exception-arguments exc)procedure
+
(os-exception-code exc)procedure
+
(os-exception-message exc)procedure
+ +

Os-exception objects are raised by procedures which access the host +operating-system’s services when the requested operation fails. The +parameter exc must be a os-exception object. +

+

The procedure os-exception? returns +#t when obj is a os-exception +object and #f otherwise. +

+

The procedure os-exception-procedure +returns the procedure that raised exc. +

+

The procedure os-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

The procedure os-exception-code returns an exact integer error +code that can be converted to a string by the err-code->string +procedure. Note that the error code is operating-system dependent. +

+

The procedure os-exception-message returns +#f or a string giving details of the exception in a +human-readable form. +

+

For example: +

+
 
> (define (handler exc)
+    (if (os-exception? exc)
+        (list (os-exception-procedure exc)
+              (os-exception-arguments exc)
+              (err-code->string (os-exception-code exc))
+              (os-exception-message exc))
+        'not-os-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (host-info "x.y.z")))
+(#<procedure #2 host-info> ("x.y.z") "Unknown host" #f)
+
+ + + +
(no-such-file-or-directory-exception? obj)procedure
+
(no-such-file-or-directory-exception-procedure exc)procedure
+
(no-such-file-or-directory-exception-arguments exc)procedure
+ +

No-such-file-or-directory-exception objects are raised by procedures +which access the filesystem (such as open-input-file and +directory-files) when the path specified can’t be found on the +filesystem. The parameter exc must be a +no-such-file-or-directory-exception object. +

+

The procedure no-such-file-or-directory-exception? returns +#t when obj is a no-such-file-or-directory-exception +object and #f otherwise. +

+

The procedure no-such-file-or-directory-exception-procedure +returns the procedure that raised exc. +

+

The procedure no-such-file-or-directory-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (no-such-file-or-directory-exception? exc)
+        (list (no-such-file-or-directory-exception-procedure exc)
+              (no-such-file-or-directory-exception-arguments exc))
+        'not-no-such-file-or-directory-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (with-input-from-file "nofile" read)))
+(#<procedure #2 with-input-from-file> ("nofile" #<procedure #3 read>))
+
+ + + +
(unbound-os-environment-variable-exception? obj)procedure
+
(unbound-os-environment-variable-exception-procedure exc)procedure
+
(unbound-os-environment-variable-exception-arguments exc)procedure
+ +

Unbound-os-environment-variable-exception objects are raised when an +unbound operating-system environment variable is accessed by the +procedures getenv and setenv. The parameter exc +must be an unbound-os-environment-variable-exception object. +

+

The procedure unbound-os-environment-variable-exception? returns +#t when obj is an unbound-os-environment-variable-exception +object and #f otherwise. +

+

The procedure unbound-os-environment-variable-exception-procedure +returns the procedure that raised exc. +

+

The procedure unbound-os-environment-variable-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (unbound-os-environment-variable-exception? exc)
+        (list (unbound-os-environment-variable-exception-procedure exc)
+              (unbound-os-environment-variable-exception-arguments exc))
+        'not-unbound-os-environment-variable-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (getenv "DOES_NOT_EXIST")))
+(#<procedure #2 getenv> ("DOES_NOT_EXIST"))
+
+ + + +
+ + + + + + + + + + + +
Back: 15.3 Exception objects related to the host environmentForward: 15.5 Exception objects related to C-interface   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.4 Exception objects related to threads

+ +
(scheduler-exception? obj)procedure
+
(scheduler-exception-reason exc)procedure
+ +

Scheduler-exception objects are raised by the scheduler when some +operation requested from the host operating system failed +(e.g. checking the status of the devices in order to wake up threads +waiting to perform I/O on these devices). The parameter exc +must be a scheduler-exception object. +

+

The procedure scheduler-exception? returns +#t when obj is a scheduler-exception +object and #f otherwise. +

+

The procedure scheduler-exception-reason returns the +os-exception object that describes the failure detected by the +scheduler. +

+ + +
(deadlock-exception? obj)procedure
+ +

Deadlock-exception objects are raised when the scheduler discovers +that all threads are blocked and can make no further progress. In +that case the scheduler unblocks the primordial-thread and forces it +to raise a deadlock-exception object. +

+

The procedure deadlock-exception? returns #t when +obj is a deadlock-exception object and #f otherwise. +

+

For example: +

+
 
> (define (handler exc)
+    (if (deadlock-exception? exc)
+        exc
+        'not-deadlock-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (read (open-vector))))
+#<deadlock-exception #2>
+
+ + + +
(abandoned-mutex-exception? obj)procedure
+ +

Abandoned-mutex-exception objects are raised when the current thread +locks a mutex that was owned by a thread which terminated (see +mutex-lock!). +

+

The procedure abandoned-mutex-exception? returns +#t when obj is a abandoned-mutex-exception +object and #f otherwise. +

+

For example: +

+
 
> (define (handler exc)
+    (if (abandoned-mutex-exception? exc)
+        exc
+        'not-abandoned-mutex-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (let ((m (make-mutex)))
+        (thread-join!
+          (thread-start!
+            (make-thread
+              (lambda () (mutex-lock! m)))))
+        (mutex-lock! m))))
+#<abandoned-mutex-exception #2>
+
+ + + +
(join-timeout-exception? obj)procedure
+
(join-timeout-exception-procedure exc)procedure
+
(join-timeout-exception-arguments exc)procedure
+ +

Join-timeout-exception objects are raised when a call to the +thread-join! procedure reaches its timeout before the target +thread terminates and a timeout-value parameter is not specified. The +parameter exc must be a join-timeout-exception object. +

+

The procedure join-timeout-exception? returns +#t when obj is a join-timeout-exception +object and #f otherwise. +

+

The procedure join-timeout-exception-procedure +returns the procedure that raised exc. +

+

The procedure join-timeout-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (join-timeout-exception? exc)
+        (list (join-timeout-exception-procedure exc)
+              (join-timeout-exception-arguments exc))
+        'not-join-timeout-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (thread-join!
+        (thread-start!
+          (make-thread
+            (lambda () (thread-sleep! 10))))
+        5)))
+(#<procedure #2 thread-join!> (#<thread #3> 5))
+
+ + + +
(started-thread-exception? obj)procedure
+
(started-thread-exception-procedure exc)procedure
+
(started-thread-exception-arguments exc)procedure
+ +

Started-thread-exception objects are raised when the target thread of +a call to the procedure thread-start! is already started. The +parameter exc must be a started-thread-exception object. +

+

The procedure started-thread-exception? returns +#t when obj is a started-thread-exception +object and #f otherwise. +

+

The procedure started-thread-exception-procedure +returns the procedure that raised exc. +

+

The procedure started-thread-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (started-thread-exception? exc)
+        (list (started-thread-exception-procedure exc)
+              (started-thread-exception-arguments exc))
+        'not-started-thread-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (let ((t (make-thread (lambda () (expt 2 1000)))))
+        (thread-start! t)
+        (thread-start! t))))
+(#<procedure #2 thread-start!> (#<thread #3>))
+
+ + + +
(terminated-thread-exception? obj)procedure
+
(terminated-thread-exception-procedure exc)procedure
+
(terminated-thread-exception-arguments exc)procedure
+ +

Terminated-thread-exception objects are raised when the +thread-join! procedure is called and the target thread has +terminated as a result of a call to the thread-terminate! +procedure. The parameter exc must be a +terminated-thread-exception object. +

+

The procedure terminated-thread-exception? returns +#t when obj is a terminated-thread-exception +object and #f otherwise. +

+

The procedure terminated-thread-exception-procedure +returns the procedure that raised exc. +

+

The procedure terminated-thread-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (terminated-thread-exception? exc)
+        (list (terminated-thread-exception-procedure exc)
+              (terminated-thread-exception-arguments exc))
+        'not-terminated-thread-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (thread-join!
+        (thread-start!
+          (make-thread
+            (lambda () (thread-terminate! (current-thread))))))))
+(#<procedure #2 thread-join!> (#<thread #3>))
+
+ + + +
(uncaught-exception? obj)procedure
+
(uncaught-exception-procedure exc)procedure
+
(uncaught-exception-arguments exc)procedure
+
(uncaught-exception-reason exc)procedure
+ +

Uncaught-exception objects are raised when an object is raised in a +thread and that thread does not handle it (i.e. the thread terminated +because it did not catch an exception it raised). The parameter +exc must be an uncaught-exception object. +

+

The procedure uncaught-exception? returns +#t when obj is an uncaught-exception +object and #f otherwise. +

+

The procedure uncaught-exception-procedure +returns the procedure that raised exc. +

+

The procedure uncaught-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

The procedure uncaught-exception-reason returns the object that +was raised by the thread and not handled by that thread. +

+

For example: +

+
 
> (define (handler exc)
+    (if (uncaught-exception? exc)
+        (list (uncaught-exception-procedure exc)
+              (uncaught-exception-arguments exc)
+              (uncaught-exception-reason exc))
+        'not-uncaught-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (thread-join!
+        (thread-start!
+          (make-thread
+            (lambda () (open-input-file "data" 99)))))))
+(#<procedure #2 thread-join!>
+ (#<thread #3>)
+ #<wrong-number-of-arguments-exception #4>)
+
+ + + +
+ + + + + + + + + + + +
Back: 15.4 Exception objects related to threadsForward: 15.6 Exception objects related to the reader   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.5 Exception objects related to C-interface

+ +
(cfun-conversion-exception? obj)procedure
+
(cfun-conversion-exception-procedure exc)procedure
+
(cfun-conversion-exception-arguments exc)procedure
+
(cfun-conversion-exception-code exc)procedure
+
(cfun-conversion-exception-message exc)procedure
+ +

Cfun-conversion-exception objects are raised by the C-interface when +converting between the Scheme representation and the C representation +of a value during a call from Scheme to C. The parameter exc +must be a cfun-conversion-exception object. +

+

The procedure cfun-conversion-exception? returns #t when +obj is a cfun-conversion-exception object and #f +otherwise. +

+

The procedure cfun-conversion-exception-procedure returns the +procedure that raised exc. +

+

The procedure cfun-conversion-exception-arguments returns the +list of arguments of the procedure that raised exc. +

+

The procedure cfun-conversion-exception-code returns an exact +integer error code that can be converted to a string by the +err-code->string procedure. +

+

The procedure cfun-conversion-exception-message returns +#f or a string giving details of the exception in a +human-readable form. +

+

For example: +

+
 
$ cat test1.scm
+(define weird
+  (c-lambda (char-string) nonnull-char-string
+    "___result = ___arg1;"))
+$ gsc test1.scm
+$ gsi
+Gambit v4.6.1
+
+> (load "test1")
+"/Users/feeley/gambit/doc/test1.o1"
+> (weird "hello")
+"hello"
+> (define (handler exc)
+    (if (cfun-conversion-exception? exc)
+        (list (cfun-conversion-exception-procedure exc)
+              (cfun-conversion-exception-arguments exc)
+              (err-code->string (cfun-conversion-exception-code exc))
+              (cfun-conversion-exception-message exc))
+        'not-cfun-conversion-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (weird 'not-a-string)))
+(#<procedure #2 weird>
+ (not-a-string)
+ "(Argument 1) Can't convert to C char-string"
+ #f)
+> (with-exception-catcher
+    handler
+    (lambda () (weird #f)))
+(#<procedure #2 weird>
+ (#f)
+ "Can't convert result from C nonnull-char-string"
+ #f)
+
+ + + +
(sfun-conversion-exception? obj)procedure
+
(sfun-conversion-exception-procedure exc)procedure
+
(sfun-conversion-exception-arguments exc)procedure
+
(sfun-conversion-exception-code exc)procedure
+
(sfun-conversion-exception-message exc)procedure
+ +

Sfun-conversion-exception objects are raised by the C-interface when +converting between the Scheme representation and the C representation +of a value during a call from C to Scheme. The parameter exc +must be a sfun-conversion-exception object. +

+

The procedure sfun-conversion-exception? returns #t when +obj is a sfun-conversion-exception object and #f +otherwise. +

+

The procedure sfun-conversion-exception-procedure returns the +procedure that raised exc. +

+

The procedure sfun-conversion-exception-arguments returns the +list of arguments of the procedure that raised exc. +

+

The procedure sfun-conversion-exception-code returns an exact +integer error code that can be converted to a string by the +err-code->string procedure. +

+

The procedure sfun-conversion-exception-message returns +#f or a string giving details of the exception in a +human-readable form. +

+

For example: +

+
 
$ cat test2.scm
+(c-define (f str) (nonnull-char-string) int "f" ""
+  (string->number str))
+(define t1 (c-lambda () int "___result = f (\"123\");"))
+(define t2 (c-lambda () int "___result = f (0);"))
+(define t3 (c-lambda () int "___result = f (\"1.5\");"))
+$ gsc test2.scm
+$ gsi
+Gambit v4.6.1
+
+> (load "test2")
+"/u/feeley/test2.o1"
+> (t1)
+123
+> (define (handler exc)
+    (if (sfun-conversion-exception? exc)
+        (list (sfun-conversion-exception-procedure exc)
+              (sfun-conversion-exception-arguments exc)
+              (err-code->string (sfun-conversion-exception-code exc))
+              (sfun-conversion-exception-message exc))
+        'not-sfun-conversion-exception))
+> (with-exception-catcher handler t2)
+(#<procedure #2 f>
+ ()
+ "(Argument 1) Can't convert from C nonnull-char-string"
+ #f)
+> (with-exception-catcher handler t3)
+(#<procedure #2 f> () "Can't convert result to C int" #f)
+
+ + + +
(multiple-c-return-exception? obj)procedure
+ +

Multiple-c-return-exception objects are raised by the C-interface when +a C to Scheme procedure call returns and that call’s stack frame is no +longer on the C stack because the call has already returned, or has +been removed from the C stack by a longjump. +

+

The procedure multiple-c-return-exception? returns #t +when obj is a multiple-c-return-exception object and #f +otherwise. +

+

For example: +

+
 
$ cat test3.scm
+(c-define (f str) (char-string) scheme-object "f" ""
+  (pp (list 'entry 'str= str))
+  (let ((k (call-with-current-continuation (lambda (k) k))))
+    (pp (list 'exit 'k= k))
+    k))
+(define scheme-to-c-to-scheme-and-back
+  (c-lambda (char-string) scheme-object
+    "___result = f (___arg1);"))
+$ gsc test3.scm
+$ gsi
+Gambit v4.6.1
+
+> (load "test3")
+"/Users/feeley/gambit/doc/test3.o1"
+> (define (handler exc)
+    (if (multiple-c-return-exception? exc)
+        exc
+        'not-multiple-c-return-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (let ((c (scheme-to-c-to-scheme-and-back "hello")))
+        (pp c)
+        (c 999))))
+(entry str= "hello")
+(exit k= #<procedure #2>)
+#<procedure #2>
+(exit k= 999)
+#<multiple-c-return-exception #3>
+
+ + + +
+ + + + + + + + + + + +
Back: 15.5 Exception objects related to C-interfaceForward: 15.7 Exception objects related to evaluation and compilation   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.6 Exception objects related to the reader

+ +
(datum-parsing-exception? obj)procedure
+
(datum-parsing-exception-kind exc)procedure
+
(datum-parsing-exception-parameters exc)procedure
+
(datum-parsing-exception-readenv exc)procedure
+ +

Datum-parsing-exception objects are raised by the reader (i.e. the +read procedure) when the input does not conform to the grammar +for datum. The parameter exc must be a datum-parsing-exception +object. +

+

The procedure datum-parsing-exception? returns #t when +obj is a datum-parsing-exception object and #f +otherwise. +

+

The procedure datum-parsing-exception-kind returns a symbol +denoting the kind of parsing error that was encountered by the +reader when it raised exc. Here is a table of the possible +return values: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
datum-or-eof-expectedDatum or EOF expected
datum-expectedDatum expected
improperly-placed-dotImproperly placed dot
incomplete-form-eof-reachedIncomplete form, EOF reached
incomplete-formIncomplete form
character-out-of-rangeCharacter out of range
invalid-character-nameInvalid ’#\’ name
illegal-characterIllegal character
s8-expectedSigned 8 bit exact integer expected
u8-expectedUnsigned 8 bit exact integer expected
s16-expectedSigned 16 bit exact integer expected
u16-expectedUnsigned 16 bit exact integer expected
s32-expectedSigned 32 bit exact integer expected
u32-expectedUnsigned 32 bit exact integer expected
s64-expectedSigned 64 bit exact integer expected
u64-expectedUnsigned 64 bit exact integer expected
inexact-real-expectedInexact real expected
invalid-hex-escapeInvalid hexadecimal escape
invalid-escaped-characterInvalid escaped character
open-paren-expected’(’ expected
invalid-tokenInvalid token
invalid-sharp-bang-nameInvalid ’#!’ name
duplicate-label-definitionDuplicate definition for label
missing-label-definitionMissing definition for label
illegal-label-definitionIllegal definition of label
invalid-infix-syntax-characterInvalid infix syntax character
invalid-infix-syntax-numberInvalid infix syntax number
invalid-infix-syntaxInvalid infix syntax
+ +

The procedure datum-parsing-exception-parameters returns a list +of the parameters associated with the parsing error that was +encountered by the reader when it raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (datum-parsing-exception? exc)
+        (list (datum-parsing-exception-kind exc)
+              (datum-parsing-exception-parameters exc))
+        'not-datum-parsing-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (with-input-from-string "(s #\\pace)" read)))
+(invalid-character-name ("pace"))
+
+ + + +
+ + + + + + + + + + + +
Back: 15.6 Exception objects related to the readerForward: 15.8 Exception objects related to type checking   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.7 Exception objects related to evaluation and compilation

+ +
(expression-parsing-exception? obj)procedure
+
(expression-parsing-exception-kind exc)procedure
+
(expression-parsing-exception-parameters exc)procedure
+
(expression-parsing-exception-source exc)procedure
+ +

Expression-parsing-exception objects are raised by the evaluator and +compiler (i.e. the procedures eval, compile-file, etc) +when the input does not conform to the grammar for expression. The +parameter exc must be a expression-parsing-exception object. +

+

The procedure expression-parsing-exception? returns #t when +obj is a expression-parsing-exception object and #f +otherwise. +

+

The procedure expression-parsing-exception-kind returns a +symbol denoting the kind of parsing error that was encountered by the +evaluator or compiler when it raised exc. Here is a table of +the possible return values: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
id-expectedIdentifier expected
ill-formed-namespaceIll-formed namespace
ill-formed-namespace-prefixIll-formed namespace prefix
namespace-prefix-must-be-stringNamespace prefix must be a string
macro-used-as-variableMacro name can’t be used as a variable
variable-is-immutableVariable is immutable
ill-formed-macro-transformerMacro transformer must be a lambda expression
reserved-used-as-variableReserved identifier can’t be used as a variable
ill-formed-special-formIll-formed special form
cannot-open-fileCan’t open file
filename-expectedFilename expected
ill-placed-defineIll-placed ’define’
ill-placed-**includeIll-placed ’##include’
ill-placed-**define-macroIll-placed ’##define-macro’
ill-placed-**declareIll-placed ’##declare’
ill-placed-**namespaceIll-placed ’##namespace’
ill-formed-expressionIll-formed expression
unsupported-special-formInterpreter does not support
ill-placed-unquoteIll-placed ’unquote’
ill-placed-unquote-splicingIll-placed ’unquote-splicing’
parameter-must-be-idParameter must be an identifier
parameter-must-be-id-or-defaultParameter must be an identifier or default binding
duplicate-parameterDuplicate parameter in parameter list
ill-placed-dotted-rest-parameterIll-placed dotted rest parameter
parameter-expected-after-rest#!rest must be followed by a parameter
ill-formed-defaultIll-formed default binding
ill-placed-optionalIll-placed #!optional
ill-placed-restIll-placed #!rest
ill-placed-keyIll-placed #!key
key-expected-after-rest#!key expected after rest parameter
ill-placed-defaultIll-placed default binding
duplicate-variable-definitionDuplicate definition of a variable
empty-bodyBody must contain at least one expression
variable-must-be-idDefined variable must be an identifier
else-clause-not-lastElse clause must be last
ill-formed-selector-listIll-formed selector list
duplicate-variable-bindingDuplicate variable in bindings
ill-formed-binding-listIll-formed binding list
ill-formed-callIll-formed procedure call
ill-formed-cond-expandIll-formed ’cond-expand’
unfulfilled-cond-expandUnfulfilled ’cond-expand’
+ +

The procedure expression-parsing-exception-parameters returns a list +of the parameters associated with the parsing error that was +encountered by the evaluator or compiler when it raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (expression-parsing-exception? exc)
+        (list (expression-parsing-exception-kind exc)
+              (expression-parsing-exception-parameters exc))
+        'not-expression-parsing-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (eval '(+ do 1))))
+(reserved-used-as-variable (do))
+
+ + + +
(unbound-global-exception? obj)procedure
+
(unbound-global-exception-variable exc)procedure
+
(unbound-global-exception-code exc)procedure
+
(unbound-global-exception-rte exc)procedure
+ +

Unbound-global-exception objects are raised when an unbound global +variable is accessed. The parameter exc must be an +unbound-global-exception object. +

+

The procedure unbound-global-exception? returns +#t when obj is an unbound-global-exception +object and #f otherwise. +

+

The procedure unbound-global-exception-variable returns a +symbol identifying the unbound global variable. +

+

For example: +

+
 
> (define (handler exc)
+    (if (unbound-global-exception? exc)
+        (list 'variable= (unbound-global-exception-variable exc))
+        'not-unbound-global-exception))
+> (with-exception-catcher
+    handler
+    (lambda () foo))
+(variable= foo)
+
+ + + +
+ + + + + + + + + + + +
Back: 15.7 Exception objects related to evaluation and compilationForward: 15.9 Exception objects related to procedure call   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.8 Exception objects related to type checking

+ +
(type-exception? obj)procedure
+
(type-exception-procedure exc)procedure
+
(type-exception-arguments exc)procedure
+
(type-exception-arg-num exc)procedure
+
(type-exception-type-id exc)procedure
+ +

Type-exception objects are raised when a primitive procedure is called +with an argument of incorrect type (i.e. when a run time type-check +fails). The parameter exc must be a type-exception object. +

+

The procedure type-exception? returns +#t when obj is a type-exception +object and #f otherwise. +

+

The procedure type-exception-procedure +returns the procedure that raised exc. +

+

The procedure type-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

The procedure type-exception-arg-num returns the position of the +argument whose type is incorrect. Position 1 is the first argument. +

+

The procedure type-exception-type-id returns an identifier of +the type expected. The type-id can be a symbol, such as number +and string-or-nonnegative-fixnum, or a record type descriptor. +

+

For example: +

+
 
> (define (handler exc)
+    (if (type-exception? exc)
+        (list (type-exception-procedure exc)
+              (type-exception-arguments exc)
+              (type-exception-arg-num exc)
+              (type-exception-type-id exc))
+        'not-type-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (vector-ref '#(a b c) 'foo)))
+(#<procedure #2 vector-ref> (#(a b c) foo) 2 exact-integer)
+> (with-exception-catcher
+    handler
+    (lambda () (time->seconds 'foo)))
+(#<procedure #3 time->seconds> (foo) 1 #<type #4 time>)
+
+ + + +
(range-exception? obj)procedure
+
(range-exception-procedure exc)procedure
+
(range-exception-arguments exc)procedure
+
(range-exception-arg-num exc)procedure
+ +

Range-exception objects are raised when a numeric parameter is not in +the allowed range. The parameter exc must be a range-exception +object. +

+

The procedure range-exception? returns #t when obj +is a range-exception object and #f otherwise. +

+

The procedure range-exception-procedure +returns the procedure that raised exc. +

+

The procedure range-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

The procedure range-exception-arg-num returns the position of +the argument which is not in the allowed range. Position 1 is the +first argument. +

+

For example: +

+
 
> (define (handler exc)
+    (if (range-exception? exc)
+        (list (range-exception-procedure exc)
+              (range-exception-arguments exc)
+              (range-exception-arg-num exc))
+        'not-range-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (string-ref "abcde" 10)))
+(#<procedure #2 string-ref> ("abcde" 10) 2)
+
+ + + +
(divide-by-zero-exception? obj)procedure
+
(divide-by-zero-exception-procedure exc)procedure
+
(divide-by-zero-exception-arguments exc)procedure
+ +

Divide-by-zero-exception objects are raised when a division by zero is +attempted. The parameter exc must be a divide-by-zero-exception +object. +

+

The procedure divide-by-zero-exception? returns +#t when obj is a divide-by-zero-exception +object and #f otherwise. +

+

The procedure divide-by-zero-exception-procedure +returns the procedure that raised exc. +

+

The procedure divide-by-zero-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (divide-by-zero-exception? exc)
+        (list (divide-by-zero-exception-procedure exc)
+              (divide-by-zero-exception-arguments exc))
+        'not-divide-by-zero-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (/ 5 0 7)))
+(#<procedure #2 /> (5 0 7))
+
+ + + +
(improper-length-list-exception? obj)procedure
+
(improper-length-list-exception-procedure exc)procedure
+
(improper-length-list-exception-arguments exc)procedure
+
(improper-length-list-exception-arg-num exc)procedure
+ +

Improper-length-list-exception objects are raised by the map +and for-each procedures when they are called with two or more +list arguments and the lists are not of the same length. The +parameter exc must be an improper-length-list-exception object. +

+

The procedure improper-length-list-exception? returns +#t when obj is an improper-length-list-exception +object and #f otherwise. +

+

The procedure improper-length-list-exception-procedure +returns the procedure that raised exc. +

+

The procedure improper-length-list-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

The procedure improper-length-list-exception-arg-num returns +the position of the argument whose length is the shortest. Position 1 +is the first argument. +

+

For example: +

+
 
> (define (handler exc)
+    (if (improper-length-list-exception? exc)
+        (list (improper-length-list-exception-procedure exc)
+              (improper-length-list-exception-arguments exc)
+              (improper-length-list-exception-arg-num exc))
+        'not-improper-length-list-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (map + '(1 2) '(3) '(4 5))))
+(#<procedure #2 map> (#<procedure #3 +> (1 2) (3) (4 5)) 3)
+
+ + + +
+ + + + + + + + + + + +
Back: 15.8 Exception objects related to type checkingForward: 15.10 Other exception objects   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.9 Exception objects related to procedure call

+ +
(wrong-number-of-arguments-exception? obj)procedure
+
(wrong-number-of-arguments-exception-procedure exc)procedure
+
(wrong-number-of-arguments-exception-arguments exc)procedure
+ +

Wrong-number-of-arguments-exception objects are raised when a +procedure is called with the wrong number of arguments. The parameter +exc must be a wrong-number-of-arguments-exception object. +

+

The procedure wrong-number-of-arguments-exception? returns +#t when obj is a wrong-number-of-arguments-exception +object and #f otherwise. +

+

The procedure wrong-number-of-arguments-exception-procedure +returns the procedure that raised exc. +

+

The procedure wrong-number-of-arguments-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (wrong-number-of-arguments-exception? exc)
+        (list (wrong-number-of-arguments-exception-procedure exc)
+              (wrong-number-of-arguments-exception-arguments exc))
+        'not-wrong-number-of-arguments-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (open-input-file "data" 99)))
+(#<procedure #2 open-input-file> ("data" 99))
+
+ + + +
(number-of-arguments-limit-exception? obj)procedure
+
(number-of-arguments-limit-exception-procedure exc)procedure
+
(number-of-arguments-limit-exception-arguments exc)procedure
+ +

Number-of-arguments-limit-exception objects are raised by the +apply procedure when the procedure being called is passed more +than 8192 arguments. The parameter exc must be a +number-of-arguments-limit-exception object. +

+

The procedure number-of-arguments-limit-exception? returns +#t when obj is a number-of-arguments-limit-exception +object and #f otherwise. +

+

The procedure number-of-arguments-limit-exception-procedure +returns the target procedure of the call to apply that raised +exc. +

+

The procedure number-of-arguments-limit-exception-arguments +returns the list of arguments of the target procedure of the call to +apply that raised exc. +

+

For example: +

+
 
> (define (iota n) (if (= n 0) '() (cons n (iota (- n 1)))))
+> (define (handler exc)
+    (if (number-of-arguments-limit-exception? exc)
+        (list (number-of-arguments-limit-exception-procedure exc)
+              (length (number-of-arguments-limit-exception-arguments exc)))
+        'not-number-of-arguments-limit-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (apply + 1 2 3 (iota 8190))))
+(#<procedure #2 +> 8193)
+
+ + + +
(nonprocedure-operator-exception? obj)procedure
+
(nonprocedure-operator-exception-operator exc)procedure
+
(nonprocedure-operator-exception-arguments exc)procedure
+
(nonprocedure-operator-exception-code exc)procedure
+
(nonprocedure-operator-exception-rte exc)procedure
+ +

Nonprocedure-operator-exception objects are raised when a procedure +call is executed and the operator position is not a procedure. The +parameter exc must be an nonprocedure-operator-exception object. +

+

The procedure nonprocedure-operator-exception? returns +#t when obj is an nonprocedure-operator-exception +object and #f otherwise. +

+

The procedure nonprocedure-operator-exception-operator returns +the value in operator position of the procedure call that raised +exc. +

+

The procedure nonprocedure-operator-exception-arguments returns +the list of arguments of the procedure call that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (nonprocedure-operator-exception? exc)
+        (list (nonprocedure-operator-exception-operator exc)
+              (nonprocedure-operator-exception-arguments exc))
+        'not-nonprocedure-operator-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (11 22 33)))
+(11 (22 33))
+
+ + + +
(unknown-keyword-argument-exception? obj)procedure
+
(unknown-keyword-argument-exception-procedure exc)procedure
+
(unknown-keyword-argument-exception-arguments exc)procedure
+ +

Unknown-keyword-argument-exception objects are raised when a procedure +accepting keyword arguments is called and one of the keywords supplied +is not among those that are expected. The parameter exc must be +an unknown-keyword-argument-exception object. +

+

The procedure unknown-keyword-argument-exception? returns +#t when obj is an unknown-keyword-argument-exception +object and #f otherwise. +

+

The procedure unknown-keyword-argument-exception-procedure +returns the procedure that raised exc. +

+

The procedure unknown-keyword-argument-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (unknown-keyword-argument-exception? exc)
+        (list (unknown-keyword-argument-exception-procedure exc)
+              (unknown-keyword-argument-exception-arguments exc))
+        'not-unknown-keyword-argument-exception))
+> (with-exception-catcher
+    handler
+    (lambda () ((lambda (#!key (foo 5)) foo) bar: 11)))
+(#<procedure #2> (bar: 11))
+
+ + + +
(keyword-expected-exception? obj)procedure
+
(keyword-expected-exception-procedure exc)procedure
+
(keyword-expected-exception-arguments exc)procedure
+ +

Keyword-expected-exception objects are raised when a procedure +accepting keyword arguments is called and a nonkeyword was supplied +where a keyword was expected. The parameter exc must be an +keyword-expected-exception object. +

+

The procedure keyword-expected-exception? returns +#t when obj is an keyword-expected-exception +object and #f otherwise. +

+

The procedure keyword-expected-exception-procedure +returns the procedure that raised exc. +

+

The procedure keyword-expected-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (keyword-expected-exception? exc)
+        (list (keyword-expected-exception-procedure exc)
+              (keyword-expected-exception-arguments exc))
+        'not-keyword-expected-exception))
+> (with-exception-catcher
+    handler
+    (lambda () ((lambda (#!key (foo 5)) foo) 11 22)))
+(#<procedure #2> (11 22))
+
+ + + +
+ + + + + + + + + + + +
Back: 15.9 Exception objects related to procedure callForward: 16. Host environment   FastBack: 15. ExceptionsUp: 15. ExceptionsFastForward: 16. Host environmentTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

15.10 Other exception objects

+ +
(error-exception? obj)procedure
+
(error-exception-message exc)procedure
+
(error-exception-parameters exc)procedure
+
(error message obj)procedure
+ +

Error-exception objects are raised when the error procedure is +called. The parameter exc must be an error-exception +object. +

+

The procedure error-exception? returns +#t when obj is an error-exception +object and #f otherwise. +

+

The procedure error-exception-message returns the first +argument of the call to error that raised exc. +

+

The procedure error-exception-parameters returns the list of +arguments, starting with the second argument, of the call to +error that raised exc. +

+

The error procedure raises an error-exception object whose +message field is message and parameters field is the list of +values obj…. +

+

For example: +

+
 
> (define (handler exc)
+    (if (error-exception? exc)
+        (list (error-exception-message exc)
+              (error-exception-parameters exc))
+        'not-error-exception))
+> (with-exception-catcher
+    handler
+    (lambda () (error "unexpected object:" 123)))
+("unexpected object:" (123))
+
+ + + +
+ + + + + + + + + + + +
Back: 15.10 Other exception objectsForward: 16.1 Handling of file names   FastBack: 15. ExceptionsUp: Gambit-CFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16. Host environment

+ +

The host environment is the set of resources, such as the filesystem, +network and processes, that are managed by the operating system within +which the Scheme program is executing. This chapter specifies how the +host environment can be accessed from within the Scheme program. +

+

In this chapter we say that the Scheme program being executed is a +process, even though the concept of process does not exist in some +operating systems supported by Gambit (e.g. MSDOS). +

+ + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 16. Host environmentForward: 16.2 Filesystem operations   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.1 Handling of file names

+ + + + + + + + +

Gambit uses a naming convention for files that is compatible with +the one used by the host environment but extended to allow +referring to the home directory of the current user or some +specific user and the installation directories. +

+

A path is a string that denotes a file, for example +"src/readme.txt". Each component of a path is separated by a +/ under UNIX and Mac OS X and by a / or \ under +MSDOS and Microsoft Windows. A leading separator indicates an +absolute path under UNIX, Mac OS X, MSDOS and Microsoft Windows. A +path which does not contain a path separator is relative to the +current working directory on all operating systems. A volume +specifier such as C: may prefix a file name under MSDOS and +Microsoft Windows. +

+ +

A path which starts with the characters ~~ denotes a file in an +installation directory. If nothing follows the ~~ then the +directory denoted is the central installation directory. Otherwise +what follows the ~~ is the name of the installation directory, +for example ~~lib denotes the lib installation +directory. Note that the location of the installation directories may +be overridden by using the -:=DIRECTORY and +-:~~DIR=DIRECTORY runtime options or by defining +the GAMBCOPT environment variable. +

+ +

A path which starts with the character ~ not followed by +~ denotes a file in the user’s home directory. The user’s home +directory is contained in the HOME environment variable under +UNIX, Mac OS X, MSDOS and Microsoft Windows. Under MSDOS and +Microsoft Windows, if the HOME environment variable is not +defined, the environment variables HOMEDRIVE and +HOMEPATH are concatenated if they are defined. If this fails +to yield a home directory, the central installation directory is used +instead. +

+ +

A path which starts with the characters ~username +denotes a file in the home directory of the given user. Under UNIX +and Mac OS X this is found using the password file. There is no +equivalent under MSDOS and Microsoft Windows. +

+
(current-directory [new-current-directory])procedure
+ + +

The parameter object current-directory is bound to the current +working directory. Calling this procedure with no argument returns +the absolute normalized path of the directory and calling this +procedure with one argument sets the directory to +new-current-directory. The initial binding of this parameter +object is the current working directory of the current process. The +path returned by current-directory always contains a trailing +directory separator. Modifications of the parameter object do not +change the current working directory of the current process (i.e. +that is accessible with the UNIX getcwd() function and the +Microsoft Windows GetCurrentDirectory function). It is an +error to mutate the string returned by current-directory. +

+

For example under UNIX: +

+
 
> (current-directory)
+"/Users/feeley/gambit/doc/"
+> (current-directory "..")
+> (current-directory)
+"/Users/feeley/gambit/"
+> (path-expand "foo" "~~")
+"/usr/local/Gambit-C/foo"
+> (parameterize ((current-directory "~~")) (path-expand "foo"))
+"/usr/local/Gambit-C/foo"
+
+ + + +
(path-expand path [origin-directory])procedure
+ + + +

The procedure path-expand takes the path of a file or directory +and returns an expanded path, which is an absolute path when +path or origin-directory are absolute paths. +The optional origin-directory parameter, which defaults +to the current working directory, is the directory used to resolve +relative paths. Components of the paths path and +origin-directory need not exist. +

+

For example under UNIX: +

+
 
> (path-expand "foo")
+"/Users/feeley/gambit/doc/foo"
+> (path-expand "~/foo")
+"/Users/feeley/foo"
+> (path-expand "~~lib/foo")
+"/usr/local/Gambit-C/lib/foo"
+> (path-expand "../foo")
+"/Users/feeley/gambit/doc/../foo"
+> (path-expand "foo" "")
+"foo"
+> (path-expand "foo" "/tmp")
+"/tmp/foo"
+> (path-expand "this/file/does/not/exist")
+"/Users/feeley/gambit/doc/this/file/does/not/exist"
+> (path-expand "")
+"/Users/feeley/gambit/doc/"
+
+ + + +
(path-normalize path [allow-relative? [origin-directory]])procedure
+ + +

The procedure path-normalize takes a path of a file or +directory and returns its normalized path. The optional +origin-directory parameter, which defaults to the current +working directory, is the directory used to resolve relative paths. +All components of the paths path and +origin-directory must exist, except possibly the last +component of path. A normalized path is a path +containing no redundant parts and which is consistent with the current +structure of the filesystem. A normalized path of a directory will +always end with a path separator (i.e. /, \, or : +depending on the operating system). The optional +allow-relative? parameter, which defaults to #f, +indicates if the path returned can be expressed relatively to +origin-directory: a #f requests an absolute path, +the symbol shortest requests the shortest of the absolute and +relative paths, and any other value requests the relative path. The +shortest path is useful for interaction with the user because short +relative paths are typically easier to read than long absolute paths. +

+

For example under UNIX: +

+
 
> (path-expand "../foo")
+"/Users/feeley/gambit/doc/../foo"
+> (path-normalize "../foo")
+"/Users/feeley/gambit/foo"
+> (path-normalize "this/file/does/not/exist")
+*** ERROR IN (console)@3.1 -- No such file or directory
+(path-normalize "this/file/does/not/exist")
+
+ + + +
(path-extension path)procedure
+
(path-strip-extension path)procedure
+
(path-directory path)procedure
+
(path-strip-directory path)procedure
+
(path-strip-trailing-directory-separator path)procedure
+
(path-volume path)procedure
+
(path-strip-volume path)procedure
+ +

These procedures extract various parts of a path, which need not be a +normalized path. The procedure path-extension returns the file +extension (including the period) or the empty string if there is no +extension. The procedure path-strip-extension returns the path +with the extension stripped off. The procedure path-directory +returns the file’s directory (including the last path separator) or +the empty string if no directory is specified in the path. The +procedure path-strip-directory returns the path with the +directory stripped off. The procedure +path-strip-trailing-directory-separator returns the path with +the directory separator stripped off if one is at the end of the path. +The procedure path-volume returns the file’s volume (including +the last path separator) or the empty string if no volume is specified +in the path. The procedure path-strip-volume returns the path +with the volume stripped off. +

+

For example under UNIX: +

+
 
> (path-extension "/tmp/foo")
+""
+> (path-extension "/tmp/foo.txt")
+".txt"
+> (path-strip-extension "/tmp/foo.txt")
+"/tmp/foo"
+> (path-directory "/tmp/foo.txt")
+"/tmp/"
+> (path-strip-directory "/tmp/foo.txt")
+"foo.txt"
+> (path-strip-trailing-directory-separator "/usr/local/bin/")
+"/usr/local/bin"
+> (path-strip-trailing-directory-separator "/usr/local/bin")
+"/usr/local/bin"
+> (path-volume "/tmp/foo.txt")
+""
+> (path-volume "C:/tmp/foo.txt")
+"" ; result is "C:" under Microsoft Windows
+> (path-strip-volume "C:/tmp/foo.txt")
+"C:/tmp/foo.txt" ; result is "/tmp/foo.txt" under Microsoft Windows
+
+ + + +
+ + + + + + + + + + + +
Back: 16.1 Handling of file namesForward: 16.3 Shell command execution   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.2 Filesystem operations

+ +
(create-directory path-or-settings)procedure
+ +

This procedure creates a directory. The argument +path-or-settings is either a string denoting a filesystem path +or a list of port settings which must contain a path: setting. +Here are the settings allowed: +

+ + +

For example: +

+
 
> (create-directory "newdir")
+> (create-directory "newdir")
+*** ERROR IN (console)@2.1 -- File exists
+(create-directory "newdir")
+
+ + + +
(create-fifo path-or-settings)procedure
+ +

This procedure creates a FIFO. The argument path-or-settings is +either a string denoting a filesystem path or a list of port settings +which must contain a path: setting. Here are the settings +allowed: +

+ + +

For example: +

+
 
> (create-fifo "fifo")
+> (define a (open-input-file "fifo"))
+> (define b (open-output-file "fifo"))
+> (display "1 22 333" b)
+> (force-output b)
+> (read a)
+1
+> (read a)
+22
+
+ + + +
(create-link source-path destination-path)procedure
+ +

This procedure creates a hard link between source-path and +destination-path. The argument source-path must be a +string denoting the path of an existing file. The argument +destination-path must be a string denoting the path of the link +to create. +

+ + +
(create-symbolic-link source-path destination-path)procedure
+ +

This procedure creates a symbolic link between source-path and +destination-path. The argument source-path must be a +string denoting the path of an existing file. The argument +destination-path must be a string denoting the path of the +symbolic link to create. +

+ + +
(rename-file source-path destination-path)procedure
+ +

This procedure renames the file source-path to +destination-path. The argument source-path must be a +string denoting the path of an existing file. The argument +destination-path must be a string denoting the new path of the +file. +

+ + +
(copy-file source-path destination-path)procedure
+ +

This procedure copies the file source-path to +destination-path. The argument source-path must be a +string denoting the path of an existing file. The argument +destination-path must be a string denoting the path of the +file to create. +

+ + +
(delete-file path)procedure
+ +

This procedure deletes the file path. The argument path +must be a string denoting the path of an existing file. +

+ + +
(delete-directory path)procedure
+ +

This procedure deletes the directory path. The argument +path must be a string denoting the path of an existing +directory. +

+ + +
(directory-files [path-or-settings])procedure
+ +

This procedure returns the list of the files in a directory. The +argument path-or-settings is either a string denoting a +filesystem path to a directory or a list of settings which must +contain a path: setting. If it is not specified, +path-or-settings defaults to the current directory (the value +bound to the current-directory parameter object). Here are the +settings allowed: +

+ + +

For example: +

+
 
> (directory-files)
+("complex" "README" "simple")
+> (directory-files "../include")
+("config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
+> (directory-files (list path: "../include" ignore-hidden: #f))
+("." ".." "config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
+
+ + + +
+ + + + + + + + + + + +
Back: 16.2 Filesystem operationsForward: 16.4 Process termination   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.3 Shell command execution

+ +
(shell-command command)procedure
+ +

The procedure shell-command calls up the shell to execute +command which must be a string. This procedure returns +the exit status of the shell in the form that the C library’s +system routine returns. +

+

For example under UNIX: +

+
 
> (shell-command "ls -sk f*.scm")
+4 fact.scm   4 fib.scm
+0
+
+ + + +
+ + + + + + + + + + + +
Back: 16.3 Shell command executionForward: 16.5 Command line arguments   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.4 Process termination

+ +
(exit [status])procedure
+ +

The procedure exit causes the process to terminate with the +status status which must be an exact integer in the range 0 to +255. If it is not specified, status defaults to 0. +

+

For example under UNIX: +

+
 
$ gsi
+Gambit v4.6.1
+
+> (exit 42)
+$ echo $?
+42
+
+ + + +
+ + + + + + + + + + + +
Back: 16.4 Process terminationForward: 16.6 Environment variables   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.5 Command line arguments

+ +
(command-line)procedure
+ +

This procedure returns a list of strings corresponding to the command +line arguments, including the program file name as the first element +of the list. When the interpreter executes a Scheme script, the list +returned by command-line contains the script’s absolute path +followed by the remaining command line arguments. +

+

For example under UNIX: +

+
 
$ gsi -:d -e "(pretty-print (command-line))"
+("gsi" "-e" "(pretty-print (command-line))")
+$ cat foo
+#!/usr/local/Gambit-C/bin/gsi-script
+(pretty-print (command-line))
+$ ./foo 1 2 "3 4"
+("/u/feeley/./foo" "1" "2" "3 4")
+
+ + + +
+ + + + + + + + + + + +
Back: 16.5 Command line argumentsForward: 16.7 Measuring time   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.6 Environment variables

+ +
(getenv name [default])procedure
+
(setenv name [new-value])procedure
+ +

The procedure getenv returns the value of the environment +variable name of the current process. Variable names are +denoted with strings. A string is returned if the environment +variable is bound, otherwise default is returned if it is +specified, otherwise an exception is raised. +

+

The procedure setenv changes the binding of the environment +variable name to new-value which must be a string. +If new-value is not specified the binding is removed. +

+

For example under UNIX: +

+
 
> (getenv "HOME")
+"/Users/feeley"
+> (getenv "DOES_NOT_EXIST" #f)
+#f
+> (setenv "DOES_NOT_EXIST" "it does now")
+> (getenv "DOES_NOT_EXIST" #f)
+"it does now"
+> (setenv "DOES_NOT_EXIST")
+> (getenv "DOES_NOT_EXIST" #f)
+#f
+> (getenv "DOES_NOT_EXIST")
+*** ERROR IN (console)@7.1 -- Unbound OS environment variable
+(getenv "DOES_NOT_EXIST")
+
+ + + +
+ + + + + + + + + + + +
Back: 16.6 Environment variablesForward: 16.8 File information   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.7 Measuring time

+ +

Procedures are available for measuring real time (aka “wall” time) +and cpu time (the amount of time the cpu has been executing the +process). The resolution of the real time and cpu time clock is +operating system dependent. Typically the resolution of the cpu time +clock is rather coarse (measured in “ticks” of 1/60th or 1/100th of +a second). Real time is internally computed relative to some +arbitrary point in time using floating point numbers, which means that +there is a gradual loss of resolution as time elapses. Moreover, some +operating systems report time in number of ticks using a 32 bit +integer so the value returned by the time related procedures may +wraparound much before any significant loss of resolution occurs (for +example 2.7 years if ticks are 1/50th of a second). +

+
(current-time)procedure
+
(time? obj)procedure
+
(time->seconds time)procedure
+
(seconds->time x)procedure
+ +

The procedure current-time returns a time object +representing the current point in real time. +

+

The procedure time? returns #t when obj is a time +object and #f otherwise. +

+

The procedure time->seconds converts the time object time +into an inexact real number representing the number of seconds elapsed +since the “epoch” (which is 00:00:00 Coordinated Universal Time +01-01-1970). +

+

The procedure seconds->time converts the real number x +representing the number of seconds elapsed since the “epoch” into a +time object. +

+

For example: +

+
 
> (current-time)
+#<time #2>
+> (time? (current-time))
+#t
+> (time? 123)
+#f
+> (time->seconds (current-time))
+1083118758.63973
+> (time->seconds (current-time))
+1083118759.909163
+> (seconds->time (+ 10 (time->seconds (current-time))
+#<time #3>  ; a time object representing 10 seconds in the future
+
+ + + +
(process-times)procedure
+
(cpu-time)procedure
+
(real-time)procedure
+ +

The procedure process-times returns a three element f64vector +containing the cpu time that has been used by the program and the real +time that has elapsed since it was started. The first element +corresponds to “user” time in seconds, the second element +corresponds to “system” time in seconds and the third element is the +elapsed real time in seconds. On operating systems that can’t +differentiate user and system time, the system time is zero. On +operating systems that can’t measure cpu time, the user time is equal +to the elapsed real time and the system time is zero. +

+

The procedure cpu-time returns the cpu time in seconds that has +been used by the program (user time plus system time). +

+

The procedure real-time returns the real time that has elapsed +since the program was started. +

+

For example: +

+
 
> (process-times)
+#f64(.02794 .021754 .159926176071167)
+> (cpu-time)
+.051223
+> (real-time)
+.40660619735717773
+
+ + + +
(time expr)special form
+ +

The time special form evaluates expr and returns the +result. As a side effect it displays a message on the interaction +channel which indicates how long the evaluation took (in real time and +cpu time), how much time was spent in the garbage collector, how much +memory was allocated during the evaluation and how many minor and +major page faults occured (0 is reported if not running under UNIX). +

+

For example: +

+
 
> (define (f x)
+    (let loop ((x x) (lst '()))
+      (if (= x 0)
+          lst
+          (loop (- x 1) (cons x lst)))))
+> (length (time (f 100000)))
+(time (f 100000))
+    683 ms real time
+    558 ms cpu time (535 user, 23 system)
+    8 collections accounting for 102 ms real time (70 user, 5 system)
+    6400160 bytes allocated
+    no minor faults
+    no major faults
+100000
+
+ + + +
+ + + + + + + + + + + +
Back: 16.7 Measuring timeForward: 16.9 Group information   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.8 File information

+ +
(file-exists? path [chase?])procedure
+ +

The path argument must be a string. This procedure returns +#t when a file by that name exists, and returns #f +otherwise. +

+

When chase? is present and #f, symbolic links will not be +chased, in other words if path refers to a symbolic link, +file-exists? will return #t whether or not it points to +an existing file. +

+

For example: +

+
 
> (file-exists? "nofile")
+#f
+
+ + + +
(file-info path [chase?])procedure
+ +

This procedure accesses the filesystem to get information about the +file whose location is given by the string path. A +file-information record is returned that contains the file’s type, the +device number, the inode number, the mode (permission bits), the +number of links, the file’s user id, the file’s group id, the file’s +size in bytes, the times of last-access, last-modification and +last-change, the attributes, and the creation time. +

+

When chase? is present and #f, symbolic links will not be +chased, in other words if path refers to a symbolic link the +file-info procedure will return information about the link +rather than the file it links to. +

+

For example: +

+
 
> (file-info "/dev/tty")
+#<file-info #2
+   type: character-special
+   device: 19513156
+   inode: 20728196
+   mode: 438
+   number-of-links: 1
+   owner: 0
+   group: 0
+   size: 0
+   last-access-time: #<time #3>
+   last-modification-time: #<time #4>
+   last-change-time: #<time #5>
+   attributes: 128
+   creation-time: #<time #6>>
+
+ + + +
(file-info? obj)procedure
+ +

This procedure returns #t when obj is a file-information +record and #f otherwise. +

+

For example: +

+
 
> (file-info? (file-info "/dev/tty"))
+#t
+> (file-info? 123)
+#f
+
+ + + +
(file-info-type file-info)procedure
+ +

Returns the type field of the file-information record +file-info. The type is denoted by a symbol. +The following types are possible: +

+
+
regular
+

Regular file +

+
directory
+

Directory +

+
character-special
+

Character special device +

+
block-special
+

Block special device +

+
fifo
+

FIFO +

+
symbolic-link
+

Symbolic link +

+
socket
+

Socket +

+
unknown
+

File is of an unknown type +

+
+ +

For example: +

+
 
> (file-info-type (file-info "/dev/tty"))
+character-special
+> (file-info-type (file-info "/dev"))
+directory
+
+ + + +
(file-info-device file-info)procedure
+ +

Returns the device field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-device (file-info "/dev/tty"))
+19513156
+
+ + + +
(file-info-inode file-info)procedure
+ +

Returns the inode field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-inode (file-info "/dev/tty"))
+20728196
+
+ + + +
(file-info-mode file-info)procedure
+ +

Returns the mode field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-mode (file-info "/dev/tty"))
+438
+
+ + + +
(file-info-number-of-links file-info)procedure
+ +

Returns the number-of-links field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-number-of-links (file-info "/dev/tty"))
+1
+
+ + + +
(file-info-owner file-info)procedure
+ +

Returns the owner field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-owner (file-info "/dev/tty"))
+0
+
+ + + +
(file-info-group file-info)procedure
+ +

Returns the group field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-group (file-info "/dev/tty"))
+0
+
+ + + +
(file-info-size file-info)procedure
+ +

Returns the size field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-size (file-info "/dev/tty"))
+0
+
+ + + +
(file-info-last-access-time file-info)procedure
+ +

Returns the last-access-time field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-last-access-time (file-info "/dev/tty"))
+#<time #2>
+
+ + + +
(file-info-last-modification-time file-info)procedure
+ +

Returns the last-modification-time field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-last-modification-time (file-info "/dev/tty"))
+#<time #2>
+
+ + + +
(file-info-last-change-time file-info)procedure
+ +

Returns the last-change-time field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-last-change-time (file-info "/dev/tty"))
+#<time #2>
+
+ + + +
(file-info-attributes file-info)procedure
+ +

Returns the attributes field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-attributes (file-info "/dev/tty"))
+128
+
+ + + +
(file-info-creation-time file-info)procedure
+ +

Returns the creation-time field of the file-information record +file-info. +

+

For example: +

+
 
> (file-info-creation-time (file-info "/dev/tty"))
+#<time #2>
+
+ + + +
(file-type path)procedure
+
(file-device path)procedure
+
(file-inode path)procedure
+
(file-mode path)procedure
+
(file-number-of-links path)procedure
+
(file-owner path)procedure
+
(file-group path)procedure
+
(file-size path)procedure
+
(file-last-access-time path)procedure
+
(file-last-modification-time path)procedure
+
(file-last-change-time path)procedure
+
(file-attributes path)procedure
+
(file-creation-time path)procedure
+ +

These procedures combine a call to the file-info procedure and +a call to a file-information record field accessor. For instance +(file-type path) is equivalent to (file-info-type +(file-info path)). +

+ + +
+ + + + + + + + + + + +
Back: 16.8 File informationForward: 16.10 User information   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.9 Group information

+ +
(group-info group-name-or-id)procedure
+ +

This procedure accesses the group database to get information about the +group identified by group-name-or-id, which is the group’s symbolic +name (string) or the group’s GID (exact integer). A group-information +record is returned that contains the group’s symbolic name, the group’s +id (GID), and the group’s members (list of symbolic user names). +

+

For example: +

+
 
> (group-info "staff")
+#<group-info #2 name: "staff" gid: 20 members: ("root")>
+> (group-info 29)
+#<group-info #3
+   name: "certusers"
+   gid: 29
+   members: ("root" "jabber" "postfix" "cyrusimap")>
+> (group-info 5000)
+*** ERROR IN (console)@3.1 -- Resource temporarily unavailable
+(group-info 5000)
+
+ + + +
(group-info? obj)procedure
+ +

This procedure returns #t when obj is a group-information +record and #f otherwise. +

+

For example: +

+
 
> (group-info? (group-info "daemon"))
+#t
+> (group-info? 123)
+#f
+
+ + + +
(group-info-name group-info)procedure
+ +

Returns the symbolic name field of the group-information record +group-info. +

+

For example: +

+
 
> (group-info-name (group-info 29))
+"certusers"
+
+ + + +
(group-info-gid group-info)procedure
+ +

Returns the group id field of the group-information record +group-info. +

+

For example: +

+
 
> (group-info-gid (group-info "staff"))
+20
+
+ + + +
(group-info-members group-info)procedure
+ +

Returns the members field of the group-information record +group-info. +

+

For example: +

+
 
> (group-info-members (group-info "staff"))
+("root")
+
+ + + +
+ + + + + + + + + + + +
Back: 16.9 Group informationForward: 16.11 Host information   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.10 User information

+ +
(user-name)procedure
+ +

This procedure returns the user’s name as a string. +

+

For example: +

+
 
> (user-name)
+"feeley"
+
+ + + +
(user-info user-name-or-id)procedure
+ +

This procedure accesses the user database to get information about the +user identified by user-name-or-id, which is the user’s symbolic +name (string) or the user’s UID (exact integer). A user-information +record is returned that contains the user’s symbolic name, the user’s +id (UID), the user’s group id (GID), the path to the user’s home +directory, and the user’s login shell. +

+

For example: +

+
 
> (user-info "feeley")
+#<user-info #2
+   name: "feeley"
+   uid: 506
+   gid: 506
+   home: "/Users/feeley"
+   shell: "/bin/bash">
+> (user-info 0)
+#<user-info #3 name: "root" uid: 0 gid: 0 home: "/var/root" shell: "/bin/sh">
+> (user-info 5000)
+*** ERROR IN (console)@3.1 -- Resource temporarily unavailable
+(user-info 5000)
+
+ + + +
(user-info? obj)procedure
+ +

This procedure returns #t when obj is a user-information +record and #f otherwise. +

+

For example: +

+
 
> (user-info? (user-info "feeley"))
+#t
+> (user-info? 123)
+#f
+
+ + + +
(user-info-name user-info)procedure
+ +

Returns the symbolic name field of the user-information record +user-info. +

+

For example: +

+
 
> (user-info-name (user-info 0))
+"root"
+
+ + + +
(user-info-uid user-info)procedure
+ +

Returns the user id field of the user-information record +user-info. +

+

For example: +

+
 
> (user-info-uid (user-info "feeley"))
+506
+
+ + + +
(user-info-gid user-info)procedure
+ +

Returns the group id field of the user-information record +user-info. +

+

For example: +

+
 
> (user-info-gid (user-info "feeley"))
+506
+
+ + + +
(user-info-home user-info)procedure
+ +

Returns the home directory field of the user-information record +user-info. +

+

For example: +

+
 
> (user-info-home (user-info 0))
+"/var/root"
+
+ + + +
(user-info-shell user-info)procedure
+ +

Returns the shell field of the user-information record +user-info. +

+

For example: +

+
 
> (user-info-shell (user-info 0))
+"/bin/sh"
+
+ + + +
+ + + + + + + + + + + +
Back: 16.10 User informationForward: 16.12 Service information   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.11 Host information

+ +
(host-name)procedure
+ +

This procedure returns the machine’s host name as a string. +

+

For example: +

+
 
> (host-name)
+"mega.iro.umontreal.ca"
+
+ + + +
(host-info host-name)procedure
+ +

This procedure accesses the internet host database to get information +about the machine whose name is denoted by the string host-name. +A host-information record is returned that contains the official name +of the machine, a list of aliases (alternative names), and a non-empty +list of IP addresses for this machine. An exception is raised when +host-name does not appear in the database. +

+

For example: +

+
 
> (host-info "www.google.com")
+#<host-info #2
+   name: "www.l.google.com"
+   aliases: ("www.google.com")
+   addresses: (#u8(66 249 85 99) #u8(66 249 85 104))>
+> (host-info "unknown.domain")
+*** ERROR IN (console)@2.1 -- Unknown host
+(host-info "unknown.domain")
+
+ + + +
(host-info? obj)procedure
+ +

This procedure returns #t when obj is a host-information +record and #f otherwise. +

+

For example: +

+
 
> (host-info? (host-info "www.google.com"))
+#t
+> (host-info? 123)
+#f
+
+ + + +
(host-info-name host-info)procedure
+ +

Returns the official name field of the host-information record +host-info. +

+

For example: +

+
 
> (host-info-name (host-info "www.google.com"))
+"www.l.google.com"
+
+ + + +
(host-info-aliases host-info)procedure
+ +

Returns the aliases field of the host-information record +host-info. This field is a possibly empty list of strings. +

+

For example: +

+
 
> (host-info-aliases (host-info "www.google.com"))
+("www.google.com")
+
+ + + +
(host-info-addresses host-info)procedure
+ +

Returns the addresses field of the host-information record +host-info. This field is a non-empty list of u8vectors +denoting IP addresses. +

+

For example: +

+
 
> (host-info-addresses (host-info "www.google.com"))
+(#u8(66 249 85 99) #u8(66 249 85 104))
+
+ + + +
(address-infos [host: host] [service: service] [family: family] [socket-type: socket-type] [protocol: protocol])procedure
+ +

This procedure is an interface to the getaddrinfo system call. +It accesses the internet host database to get information about the +machine whose name is denoted by the string host and service is +denoted by the string service and network address family is +family (INET or INET6) and network socket-type is +socket-type (STREAM or DGRAM or RAW) and +network protocol is socket-type (TCP or UDP). A +list of address-information records is returned. +

+

For example: +

+
 
> (address-infos host: "ftp.at.debian.org")
+(#<address-info #2
+    family: INET6
+    socket-type: DGRAM
+    protocol: UDP
+    socket-info:
+     #<socket-info #3
+        family: INET6
+        port-number: 0
+        address: #u16(8193 2136 2 1 0 0 0 16)>>
+ #<address-info #4
+    family: INET6
+    socket-type: STREAM
+    protocol: TCP
+    socket-info:
+     #<socket-info #5
+        family: INET6
+        port-number: 0
+        address: #u16(8193 2136 2 1 0 0 0 16)>>
+ #<address-info #6
+    family: INET
+    socket-type: DGRAM
+    protocol: UDP
+    socket-info:
+     #<socket-info #7
+        family: INET
+        port-number: 0
+        address: #u8(213 129 232 18)>>
+ #<address-info #8
+    family: INET
+    socket-type: STREAM
+    protocol: TCP
+    socket-info:
+     #<socket-info #9
+        family: INET
+        port-number: 0
+        address: #u8(213 129 232 18)>>)
+> (address-infos host: "ftp.at.debian.org"
+                 family: 'INET
+                 protocol: 'TCP)
+(#<address-info #10
+    family: INET
+    socket-type: STREAM
+    protocol: TCP
+    socket-info:
+     #<socket-info #11
+        family: INET
+        port-number: 0
+        address: #u8(213 129 232 18)>>)
+> (address-infos host: "unknown.domain")
+*** ERROR IN (console)@5.1 -- nodename nor servname provided, or not known
+(address-infos host: "unknown.domain")
+
+ + + +
(address-info? obj)procedure
+ +

This procedure returns #t when obj is an address-information +record and #f otherwise. +

+

For example: +

+
 
> (map address-info?
+       (address-infos host: "ftp.at.debian.org"))
+(#t #t #t #t)
+> (address-info? 123)
+#f
+
+ + + +
(address-info-family address-info)procedure
+ +

Returns the family field of the address-information record +address-info. +

+

For example: +

+
 
> (map address-info-family
+       (address-infos host: "ftp.at.debian.org"))
+(INET6 INET6 INET INET)
+
+ + + +
(address-info-socket-type address-info)procedure
+ +

Returns the socket-type field of the address-information record +address-info. +

+

For example: +

+
 
> (map address-info-socket-type
+       (address-infos host: "ftp.at.debian.org"))
+(DGRAM STREAM DGRAM STREAM)
+
+ + + +
(address-info-protocol address-info)procedure
+ +

Returns the protocol field of the address-information record +address-info. +

+

For example: +

+
 
> (map address-info-protocol
+       (address-infos host: "ftp.at.debian.org"))
+(UDP TCP UDP TCP)
+
+ + + +
(address-info-socket-info address-info)procedure
+ +

Returns the socket-info field of the address-information record +address-info. +

+

For example: +

+
 
> (map address-info-socket-info
+       (address-infos host: "ftp.at.debian.org"))
+(#<socket-info #2
+    family: INET6
+    port-number: 0
+    address: #u16(8193 2136 2 1 0 0 0 16)>
+ #<socket-info #3
+    family: INET6
+    port-number: 0
+    address: #u16(8193 2136 2 1 0 0 0 16)>
+ #<socket-info #4
+    family: INET
+    port-number: 0
+    address: #u8(213 129 232 18)>
+ #<socket-info #5
+    family: INET
+    port-number: 0
+    address: #u8(213 129 232 18)>)
+
+ + + +
+ + + + + + + + + + + +
Back: 16.11 Host informationForward: 16.13 Protocol information   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.12 Service information

+ +
(service-info service-name-or-id)procedure
+ +

This procedure accesses the service database to get information about +the service identified by service-name-or-id, which is the +service’s symbolic name (string) or the service’s port number (exact +integer). A service-information record is returned that contains the +service’s symbolic name, a list of aliases (alternative names), the +port number (exact integer), and the protocol name (string). An +exception is raised when service-name-or-id does not appear in +the database. +

+

For example: +

+
 
> (service-info "http")
+#<service-info #2
+   name: "http"
+   aliases: ("www" "www-http")
+   port-number: 80
+   protocol: "udp">
+> (service-info 80)
+#<service-info #3
+   name: "http"
+   aliases: ("www" "www-http")
+   port-number: 80
+   protocol: "udp">
+
+ + + +
(service-info? obj)procedure
+ +

This procedure returns #t when obj is a service-information +record and #f otherwise. +

+

For example: +

+
 
> (service-info? (service-info "http"))
+#t
+> (service-info? 123)
+#f
+
+ + + +
(service-info-name service-info)procedure
+ +

Returns the symbolic name field of the service-information record +service-info. +

+

For example: +

+
 
> (service-info-name (service-info 80))
+"http"
+
+ + + +
(service-info-aliases service-info)procedure
+ +

Returns the aliases field of the service-information record +service-info. This field is a possibly empty list of strings. +

+

For example: +

+
 
> (service-info-aliases (service-info "http"))
+("www" "www-http")
+
+ + + +
(service-info-port-number service-info)procedure
+ +

Returns the service port number field of the service-information +record service-info. +

+

For example: +

+
 
> (service-info-port-number (service-info "http"))
+80
+
+ + + +
(service-info-protocol service-info)procedure
+ +

Returns the service protocol name field of the service-information +record service-info. +

+

For example: +

+
 
> (service-info-protocol (service-info "http"))
+"udp"
+
+ + + +
+ + + + + + + + + + + +
Back: 16.12 Service informationForward: 16.14 Network information   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.13 Protocol information

+ +
(protocol-info protocol-name-or-id)procedure
+ +

This procedure accesses the protocol database to get information about +the protocol identified by protocol-name-or-id, which is the +protocol’s symbolic name (string) or the protocol’s number (exact +integer). A protocol-information record is returned that contains the +protocol’s symbolic name, a list of aliases (alternative names), and +the protocol number (32 bit unsigned exact integer). An exception is +raised when protocol-name-or-id does not appear in the database. +

+

For example: +

+
 
> (protocol-info "tcp")
+#<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>
+> (protocol-info 6)
+#<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>
+
+ + + +
(protocol-info? obj)procedure
+ +

This procedure returns #t when obj is a protocol-information +record and #f otherwise. +

+

For example: +

+
 
> (protocol-info? (protocol-info "tcp"))
+#t
+> (protocol-info? 123)
+#f
+
+ + + +
(protocol-info-name protocol-info)procedure
+ +

Returns the symbolic name field of the protocol-information record +protocol-info. +

+

For example: +

+
 
> (protocol-info-name (protocol-info 6))
+"tcp"
+
+ + + +
(protocol-info-aliases protocol-info)procedure
+ +

Returns the aliases field of the protocol-information record +protocol-info. This field is a possibly empty list of strings. +

+

For example: +

+
 
> (protocol-info-aliases (protocol-info "tcp"))
+("TCP")
+
+ + + +
(protocol-info-number protocol-info)procedure
+ +

Returns the protocol number field of the protocol-information record +protocol-info. +

+

For example: +

+
 
> (protocol-info-number (protocol-info "tcp"))
+6
+
+ + + +
+ + + + + + + + + + + +
Back: 16.13 Protocol informationForward: 17. I/O and ports   FastBack: 16. Host environmentUp: 16. Host environmentFastForward: 17. I/O and portsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

16.14 Network information

+ +
(network-info network-name-or-id)procedure
+ +

This procedure accesses the network database to get information about +the network identified by network-name-or-id, which is the +network’s symbolic name (string) or the network’s number (exact +integer). A network-information record is returned that contains the +network’s symbolic name, a list of aliases (alternative names), and +the network number (32 bit unsigned exact integer). An exception is +raised when network-name-or-id does not appear in the database. +

+

For example: +

+
 
> (network-info "loopback")
+#<network-info #2
+   name: "loopback"
+   aliases: ("loopback-net")
+   number: 127>
+> (network-info 127)
+#<network-info #3
+   name: "loopback"
+   aliases: ("loopback-net")
+   number: 127>
+
+ + + +
(network-info? obj)procedure
+ +

This procedure returns #t when obj is a network-information +record and #f otherwise. +

+

For example: +

+
 
> (network-info? (network-info "loopback"))
+#t
+> (network-info? 123)
+#f
+
+ + + +
(network-info-name network-info)procedure
+ +

Returns the symbolic name field of the network-information record +network-info. +

+

For example: +

+
 
> (network-info-name (network-info 127))
+"loopback"
+
+ + + +
(network-info-aliases network-info)procedure
+ +

Returns the aliases field of the network-information record +network-info. This field is a possibly empty list of strings. +

+

For example: +

+
 
> (network-info-aliases (network-info "loopback"))
+("loopback-net")
+
+ + + +
(network-info-number network-info)procedure
+ +

Returns the network number field of the network-information record +network-info. +

+

For example: +

+
 
> (network-info-number (network-info "loopback"))
+127
+
+ + + +
+ + + + + + + + + + + +
Back: 16.14 Network informationForward: 17.1 Unidirectional and bidirectional ports   FastBack: 16. Host environmentUp: Gambit-CFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17. I/O and ports

+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 17. I/O and portsForward: 17.2 Port classes   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.1 Unidirectional and bidirectional ports

+ +

Unidirectional ports allow communication between a producer of +information and a consumer. An input-port’s producer is typically a +resource managed by the operating system (such as a file, a process or +a network connection) and the consumer is the Scheme program. The +roles are reversed for an output-port. +

+

Associated with each port are settings that affect I/O operations on +that port (encoding of characters to bytes, end-of-line encoding, type +of buffering, etc). Port settings are specified when the port is +created. Some port settings can be changed after a port is created. +

+

Bidirectional ports, also called input-output-ports, allow +communication in both directions. They are best viewed as an object +that groups two separate unidirectional ports (one in each direction). +Each direction has its own port settings and can be closed +independently from the other direction. +

+
+ + + + + + + + + + + +
Back: 17.1 Unidirectional and bidirectional portsForward: 17.3 Port settings   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.2 Port classes

+ +

The four classes of ports listed below form an inheritance hierarchy. +Operations possible for a certain class of port are also possible for +the subclasses. Only device-ports are connected to a device managed +by the operating system. For instance it is possible to create ports +that behave as a FIFO where the Scheme program is both the producer +and consumer of information (possibly one thread is the producer and +another thread is the consumer). +

+
    +
  1. +An object-port (or simply a port) provides operations to read +and write Scheme data (i.e. any Scheme object) to/from the port. It +also provides operations to force output to occur, to change the way +threads block on the port, and to close the port. Note that the class +of objects for which write/read invariance is guaranteed depends on +the particular class of port. + +
  2. +A character-port provides all the operations of an object-port, +and also operations to read and write individual characters to/from +the port. When a Scheme object is written to a character-port, it is +converted into the sequence of characters that corresponds to its +external-representation. When reading a Scheme object, an inverse +conversion occurs. Note that some Scheme objects do not have an +external textual representation that can be read back. + +
  3. +A byte-port provides all the operations of a character-port, and +also operations to read and write individual bytes to/from the port. +When a character is written to a byte-port, some encoding of that +character into a sequence of bytes will occur (for example, +#\newline will be encoded as the 2 bytes CR-LF when using +ISO-8859-1 character encoding and cr-lf end-of-line encoding, and +a non-ASCII character will generate more than 1 byte when using UTF-8 +character encoding). When reading a character, a similar decoding +occurs. + +
  4. +A device-port provides all the operations of a byte-port, and +also operations to control the operating system managed device (file, +network connection, terminal, etc) that is connected to the port. + +
+ +
+ + + + + + + + + + + +
Back: 17.2 Port classesForward: 17.4 Object-ports   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.3 Port settings

+ +

Some port settings are only valid for specific port classes whereas +some others are valid for all ports. Port settings are specified when +a port is created. The settings that are not specified will default +to some reasonable values. Keyword objects are used to name the +settings to be set. As a simple example, a device-port connected to +the file "foo" can be created using the call +

+
 
(open-input-file "foo")
+
+ +

This will use default settings for the character encoding, buffering, +etc. If the UTF-8 character encoding is desired, then the port could +be opened using the call +

+
 
(open-input-file (list path: "foo" char-encoding: 'UTF-8))
+
+ +

Here the argument of the procedure open-input-file has been +replaced by a port settings list which specifies the value of +each port setting that should not be set to the default value. Note +that some port settings have no useful default and it is therefore +required to specify a value for them, such as the path: in the +case of the file opening procedures. All port creation procedures +(i.e. named open-...) take a single argument that can either +be a port settings list or a value of a type that depends on the kind +of port being created (a path string for files, an IP port number for +socket servers, etc). +

+
+ + + + + + + + + + + +
Back: 17.3 Port settingsForward: 17.4.1 Object-port settings   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.4 Object-ports

+ + + + + + +
+ + + + + + + + + + + +
Back: 17.4 Object-portsForward: 17.4.2 Object-port operations   FastBack: 17. I/O and portsUp: 17.4 Object-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.4.1 Object-port settings

+ +

The following is a list of port settings that are valid for all types +of ports. +

+ + +
+ + + + + + + + + + + +
Back: 17.4.1 Object-port settingsForward: 17.5 Character-ports   FastBack: 17. I/O and portsUp: 17.4 Object-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.4.2 Object-port operations

+ +
(input-port? obj)procedure
+
(output-port? obj)procedure
+
(port? obj)procedure
+ +

The procedure input-port? returns #t when obj is a +unidirectional input-port or a bidirectional port and #f +otherwise. +

+

The procedure output-port? returns #t when obj is a +unidirectional output-port or a bidirectional port and #f +otherwise. +

+

The procedure port? returns #t when obj is a port +(either unidirectional or bidirectional) and #f otherwise. +

+

For example: +

+
 
> (input-port? (current-input-port))
+#t
+> (call-with-input-string "some text" output-port?)
+#f
+> (port? (current-output-port))
+#t
+
+ + + +
(read [port])procedure
+ +

This procedure reads and returns the next Scheme datum from the +input-port port. The end-of-file object is returned when the +end of the stream is reached. If it is not specified, port +defaults to the current input-port. +

+

For example: +

+
 
> (call-with-input-string "some text" read)
+some
+> (call-with-input-string "" read)
+#!eof
+
+ + + +
(read-all [port [reader]])procedure
+ +

This procedure repeatedly calls the procedure reader with +port as the sole argument and accumulates a list of each value +returned up to the end-of-file object. The procedure read-all +returns the accumulated list without the end-of-file object. If it is +not specified, port defaults to the current input-port. If it +is not specified, reader defaults to the procedure read. +

+

For example: +

+
 
> (call-with-input-string "3,2,1\ngo!" read-all)
+(3 ,2 ,1 go!)
+> (call-with-input-string "3,2,1\ngo!"
+                          (lambda (p) (read-all p read-char)))
+(#\3 #\, #\2 #\, #\1 #\newline #\g #\o #\!)
+> (call-with-input-string "3,2,1\ngo!"
+                          (lambda (p) (read-all p read-line)))
+("3,2,1" "go!")
+
+ + + +
(write obj [port])procedure
+ +

This procedure writes the Scheme datum obj to the output-port +port and the value returned is unspecified. If it is not +specified, port defaults to the current output-port. +

+

For example: +

+
 
> (write (list 'compare (list 'quote '@x) 'and (list 'unquote '@x))) 
+(compare '@x and , @x)> 
+
+ + + +
(newline [port])procedure
+ +

This procedure writes an “object separator” to the output-port +port and the value returned is unspecified. The separator +ensures that the next Scheme datum written with the write +procedure will not be confused with the latest datum that was written. +On character-ports this is done by writing the character +#\newline. On ports where successive objects are implicitly +distinct (such as “vector ports”) this procedure does nothing. +

+

Regardless of the class of a port p and assuming that the +external textual representation of the object x is readable, the +expression (begin (write x p) (newline p)) +will write to p a representation of x that can be read +back with the procedure read. If it is not specified, +port defaults to the current output-port. +

+

For example: +

+
 
> (begin (write 123) (newline) (write 456) (newline))
+123
+456
+
+ + + +
(force-output [port [level]])procedure
+ +

The procedure force-output causes the data that was written to +the output-port port to be moved closer to its destination +according to level, an exact integer in the range 0 to 2. If +port is not specified, the current output-port is used. If +level is not specified, it defaults to 0. Values of level +above 0 are equivalent to level = 0 except for device ports as +explained below. +

+

When level is 0, the output buffers of port which are +managed in the Scheme process are drained (i.e. the output operation +that was delayed due to buffering is actually performed). In the case +of a device port the data is passed to the operating system and it +becomes its responsibility to transmit the data to the device. The +operating system may implement its own buffering approach which delays +the transmission of the data to the device. +

+

When level is 1, in addition to the operations for level = +0 and if the operating system supports the functionality, the +operating system is requested to transmit the data to the device. On +UNIX this corresponds to a fsync system call. +

+

When level is 2, in addition to the operations for level = +1 and if the operating system supports the functionality, the +operating system is requested to wait until the device reports that +the data was saved by the device (e.g. actually written to disk in the +case of a file). This operation can take a long time on some +operating systems. On Mac OS X this corresponds to a fcntl +system call with operation F_FULLFSYNC. +

+

For example: +

+
 
> (define p (open-tcp-client "www.iro.umontreal.ca:80"))
+> (display "GET /\n" p)
+> (force-output p)
+> (read-line p)
+"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
+
+ + + +
(close-input-port port)procedure
+
(close-output-port port)procedure
+
(close-port port)procedure
+ +

The port argument of these procedures must be a unidirectional +or a bidirectional port. For all three procedures the value returned +is unspecified. +

+

The procedure close-input-port closes the input-port side of +port, which must not be a unidirectional output-port. +

+

The procedure close-output-port closes the output-port side of +port, which must not be a unidirectional input-port. The ouput +buffers are drained before port is closed. +

+

The procedure close-port closes all sides of the port. +Unless port is a unidirectional input-port, the output buffers +are drained before port is closed. +

+

For example: +

+
 
> (define p (open-tcp-client "www.iro.umontreal.ca:80"))
+> (display "GET /\n" p)
+> (close-output-port p)
+> (read-line p)
+"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
+
+ + + +
(input-port-timeout-set! port timeout [thunk])procedure
+
(output-port-timeout-set! port timeout [thunk])procedure
+ +

When a thread tries to perform an I/O operation on a port, the +requested operation may not be immediately possible and the thread +must wait. For example, the thread may be trying to read a line of +text from the console and the user has not typed anything yet, or the +thread may be trying to write to a network connection faster than the +network can handle. In such situations the thread normally blocks +until the operation becomes possible. +

+

It is sometimes necessary to guarantee that the thread will not block +too long. For this purpose, to each input-port and output-port is +attached a timeout and timeout-thunk. The timeout +indicates the point in time beyond which the thread should stop +waiting on an input and output operation respectively. When the +timeout is reached, the thread calls the port’s timeout-thunk. If the +timeout-thunk returns #f the thread abandons trying to perform +the operation (in the case of an input operation an end-of-file is +read and in the case of an output operation an exception is raised). +Otherwise, the thread will block again waiting for the operation to +become possible (note that if the port’s timeout has not changed the +thread will immediately call the timeout-thunk again). +

+

The procedure input-port-timeout-set! sets the timeout of the +input-port port to timeout and the timeout-thunk to +thunk. The procedure output-port-timeout-set! sets the +timeout of the output-port port to timeout and the +timeout-thunk to thunk. If it is not specified, the thunk +defaults to a thunk that returns #f. The timeout is +either a time object indicating an absolute point in time, or it is a +real number which indicates the number of seconds relative to the +moment the procedure is called. For both procedures the value +returned is unspecified. +

+

When a port is created the timeout is set to infinity (+inf.0). +This causes the thread to wait as long as needed for the operation to +become possible. Setting the timeout to a point in the past +(-inf.0) will cause the thread to attempt the I/O operation and +never block (i.e. the timeout-thunk is called if the operation is not +immediately possible). +

+

The following example shows how to cause the REPL to terminate +when the user does not enter an expression within the next 60 seconds. +

+
 
> (input-port-timeout-set! (repl-input-port) 60)
+> 
+*** EOF again to exit
+
+ + + +
+ + + + + + + + + + + +
Back: 17.4.2 Object-port operationsForward: 17.5.1 Character-port settings   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.5 Character-ports

+ + + + + + +
+ + + + + + + + + + + +
Back: 17.5 Character-portsForward: 17.5.2 Character-port operations   FastBack: 17. I/O and portsUp: 17.5 Character-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.5.1 Character-port settings

+ +

The following is a list of port settings that are valid for +character-ports. +

+ + +
+ + + + + + + + + + + +
Back: 17.5.1 Character-port settingsForward: 17.6 Byte-ports   FastBack: 17. I/O and portsUp: 17.5 Character-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.5.2 Character-port operations

+ +
(input-port-line port)procedure
+
(input-port-column port)procedure
+
(output-port-line port)procedure
+
(output-port-column port)procedure
+ +

The current character location of a character input-port is the +location of the next character to read. The current character +location of a character output-port is the location of the next +character to write. Location is denoted by a line number (the first +line is line 1) and a column number, that is the location on the +current line (the first column is column 1). The procedures +input-port-line and input-port-column return the line +location and the column location respectively of the character +input-port port. The procedures output-port-line and +output-port-column return the line location and the column +location respectively of the character output-port port. +

+

For example: +

+
 
> (call-with-output-string
+    '()
+    (lambda (p)
+      (display "abc\n123def" p)
+      (write (list (output-port-line p) (output-port-column p))
+             p)))
+"abc\n123def(2 7)"
+
+ + + +
(output-port-width port)procedure
+ +

This procedure returns the width, in characters, of the character +output-port port. The value returned is the port’s output-width +setting. +

+

For example: +

+
 
> (output-port-width (repl-output-port))
+80
+
+ + + +
(read-char [port])procedure
+ +

This procedure reads the character input-port port and returns +the character at the current character location and advances the +current character location to the next character, unless the +port is already at end-of-file in which case read-char +returns the end-of-file object. If it is not specified, port +defaults to the current input-port. +

+

For example: +

+
 
> (call-with-input-string
+    "some text"
+    (lambda (p)
+      (let ((a (read-char p))) (list a (read-char p)))))
+(#\s #\o)
+> (call-with-input-string "" read-char)
+#!eof
+
+ + + +
(peek-char [port])procedure
+ +

This procedure returns the same result as read-char but it does +not advance the current character location of the input-port +port. If it is not specified, port defaults to the +current input-port. +

+

For example: +

+
 
> (call-with-input-string
+    "some text"
+    (lambda (p)
+      (let ((a (peek-char p))) (list a (read-char p)))))
+(#\s #\s)
+> (call-with-input-string "" peek-char)
+#!eof
+
+ + + +
(write-char char [port])procedure
+ +

This procedure writes the character char to the character +output-port port and advances the current character location of +that output-port. The value returned is unspecified. If it is not +specified, port defaults to the current output-port. +

+

For example: +

+
 
> (write-char #\=)
+=> 
+
+ + + +
(read-line [port [separator [include-separator? [max-length]]]])procedure
+ +

This procedure reads characters from the character input-port +port until a specific separator or the end-of-file is +encountered and returns a string containing the sequence of characters +read. If it is specified, max-length must be a nonnegative +exact integer and it places an upper limit on the number of characters +that are read. +

+

The separator is included at the end of the string only +if it was the last character read and include-separator? is not +#f. The separator must be a character or #f (in +which case all the characters until the end-of-file are read). If it +is not specified, port defaults to the current input-port. If +it is not specified, separator defaults to #\newline. If +it is not specified, include-separator? defaults to #f. +

+

For example: +

+
 
> (define (split sep)
+    (lambda (str)
+      (call-with-input-string
+        str
+        (lambda (p)
+          (read-all p (lambda (p) (read-line p sep)))))))
+> ((split #\,) "a,b,c")
+("a" "b" "c")
+> (map (split #\,)
+       (call-with-input-string "1,2,3\n4,5"
+                               (lambda (p) (read-all p read-line))))
+(("1" "2" "3") ("4" "5"))
+> (read-line (current-input-port) #\newline #f 2)1234
+"12"
+> 34
+
+ + + +
(read-substring string start end [port [need]])procedure
+
(write-substring string start end [port])procedure
+ +

These procedures support bulk character I/O. The part of the string +string starting at index start and ending just before +index end is used as a character buffer that will be the target +of read-substring or the source of the write-substring. +The read-substring also accepts a need parameter which +must be a nonnegative fixnum. Up to end-start characters +will be transferred. The number of characters transferred, possibly +zero, is returned by these procedures. Fewer characters will be read +by read-substring if an end-of-file is read, or a timeout +occurs before all the requested characters are transferred and the +timeout thunk returns #f (see the procedure +input-port-timeout-set!), or need is specified and at +least that many characters have been read (in other words the +procedure does not block for more characters but may transfer more +characters if they are immediately available). Fewer characters will +be written by write-substring if a timeout occurs before all +the requested characters are transferred and the timeout thunk returns +#f (see the procedure output-port-timeout-set!). If it +is not specified, port defaults to the current input-port and +current output-port respectively. +

+

For example: +

+
 
> (define s (make-string 10 #\x))
+> (read-substring s 2 5)123456789
+3
+> 456789
+> s
+"xx123xxxxx"
+> (read-substring s 2 10 (current-input-port) 3)abcd
+5
+> s
+"xxabcd\nxxx"
+
+ + + +
(input-port-readtable port)procedure
+
(output-port-readtable port)procedure
+ +

These procedures return the readtable attached to the character-port +port. The port parameter of input-port-readtable +must be an input-port. The port parameter of +output-port-readtable must be an output-port. +

+ + +
(input-port-readtable-set! port readtable)procedure
+
(output-port-readtable-set! port readtable)procedure
+ +

These procedures change the readtable attached to the character-port +port to the readtable readtable. The port parameter +of input-port-readtable-set! must be an input-port. The +port parameter of output-port-readtable-set! must be an +output-port. The value returned is unspecified. +

+ + +
+ + + + + + + + + + + +
Back: 17.5.2 Character-port operationsForward: 17.6.1 Byte-port settings   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.6 Byte-ports

+ + + + + + +
+ + + + + + + + + + + +
Back: 17.6 Byte-portsForward: 17.6.2 Byte-port operations   FastBack: 17. I/O and portsUp: 17.6 Byte-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.6.1 Byte-port settings

+ +

The following is a list of port settings that are valid for +byte-ports. +

+ + +
+ + + + + + + + + + + +
Back: 17.6.1 Byte-port settingsForward: 17.7 Device-ports   FastBack: 17. I/O and portsUp: 17.6 Byte-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.6.2 Byte-port operations

+ +
(read-u8 [port])procedure
+ +

This procedure reads the byte input-port port and returns the +byte at the current byte location and advances the current byte +location to the next byte, unless the port is already at +end-of-file in which case read-u8 returns the end-of-file +object. If it is not specified, port defaults to the current +input-port. +

+

This procedure must be called when the port’s input character buffer +is empty otherwise the character-stream and byte-stream may be out of +sync due to buffering. The input character buffer is used for bulk +decoding of encoded characters (i.e. to translate the byte-stream into +a character-stream). The input character buffer is initially empty. +It is only when characters are read that it is filled with characters +obtained by decoding the byte-stream. +

+

One way to ensure that the port’s input character buffer is empty is +to call read-u8 strictly before any use of the port in a character +input operation (i.e. a call to the procedures read, +read-char, peek-char, etc). Alternatively +input-port-characters-buffered can be used to get the number of +characters in the port’s input character buffer, and to empty the +buffer with calls to read-char or read-substring. +

+

For example: +

+
 
> (call-with-input-u8vector
+    '#u8(11 22 33 44)
+    (lambda (p)
+      (let ((a (read-u8 p))) (list a (read-u8 p)))))
+(11 22)
+> (call-with-input-u8vector '#u8() read-u8)
+#!eof
+
+ + + +
(write-u8 n [port])procedure
+ +

This procedure writes the byte n to the byte output-port +port and advances the current byte location of that output-port. +The value returned is unspecified. If it is not specified, port +defaults to the current output-port. +

+

For example: +

+
 
> (call-with-output-u8vector '() (lambda (p) (write-u8 33 p)))
+#u8(33)
+
+ + + +
(read-subu8vector u8vector start end [port [need]])procedure
+
(write-subu8vector u8vector start end [port])procedure
+ +

These procedures support bulk byte I/O. The part of the u8vector +u8vector starting at index start and ending just before +index end is used as a byte buffer that will be the target of +read-subu8vector or the source of the write-subu8vector. +The read-subu8vector also accepts a need parameter which +must be a nonnegative fixnum. Up to end-start bytes will +be transferred. The number of bytes transferred, possibly zero, is +returned by these procedures. Fewer bytes will be read by +read-subu8vector if an end-of-file is read, or a timeout occurs +before all the requested bytes are transferred and the timeout thunk +returns #f (see the procedure input-port-timeout-set!), +or need is specified and at least that many bytes have been read +(in other words the procedure does not block for more bytes but may +transfer more bytes if they are immediately available). Fewer bytes +will be written by write-subu8vector if a timeout occurs before +all the requested bytes are transferred and the timeout thunk returns +#f (see the procedure output-port-timeout-set!). If it +is not specified, port defaults to the current input-port and +current output-port respectively. +

+

The procedure read-subu8vector must be called before any use of +the port in a character input operation (i.e. a call to the procedures +read, read-char, peek-char, etc) because +otherwise the character-stream and byte-stream may be out of sync due +to the port buffering. +

+

For example: +

+
 
> (define v (make-u8vector 10))
+> (read-subu8vector v 2 5)123456789
+3
+> 456789
+> v
+#u8(0 0 49 50 51 0 0 0 0 0)
+> (read-subu8vector v 2 10 (current-input-port) 3)abcd
+5
+> v
+#u8(0 0 97 98 99 100 10 0 0 0)
+
+ + + +
+ + + + + + + + + + + +
Back: 17.6.2 Byte-port operationsForward: 17.7.1 Filesystem devices   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.7 Device-ports

+ + + + + + + +
+ + + + + + + + + + + +
Back: 17.7 Device-portsForward: 17.7.2 Process devices   FastBack: 17. I/O and portsUp: 17.7 Device-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.7.1 Filesystem devices

+ +
(open-file path-or-settings)procedure
+
(open-input-file path-or-settings)procedure
+
(open-output-file path-or-settings)procedure
+
(call-with-input-file path-or-settings proc)procedure
+
(call-with-output-file path-or-settings proc)procedure
+
(with-input-from-file path-or-settings thunk)procedure
+
(with-output-to-file path-or-settings thunk)procedure
+ +

All of these procedures create a port to interface to a byte-stream +device (such as a file, console, serial port, named pipe, etc) whose +name is given by a path of the filesystem. The direction: +setting will default to the value input for the procedures +open-input-file, call-with-input-file and +with-input-from-file, to the value output for the +procedures open-output-file, call-with-output-file and +with-output-to-file, and to the value input-output for +the procedure open-file. +

+

The procedures open-file, open-input-file and +open-output-file return the port that is created. The +procedures call-with-input-file and +call-with-output-file call the procedure proc with the +port as single argument, and then return the value(s) of this call +after closing the port. The procedures with-input-from-file +and with-output-to-file dynamically bind the current input-port +and current output-port respectively to the port created for the +duration of a call to the procedure thunk with no argument. The +value(s) of the call to thunk are returned after closing the +port. +

+

The first argument of these procedures is either a string denoting a +filesystem path or a list of port settings which must contain a +path: setting. Here are the settings allowed in addition to +the generic settings of byte-ports: +

+ + +

For example: +

+
 
> (with-output-to-file
+    (list path: "nofile"
+          create: #f)
+    (lambda ()
+      (display "hello world!\n")))
+*** ERROR IN (console)@1.1 -- No such file or directory
+(with-output-to-file '(path: "nofile" create: #f) '#<procedure #2>)
+
+ + + +
(input-port-byte-position port [position [whence]])procedure
+
(output-port-byte-position port [position [whence]])procedure
+ +

When called with a single argument these procedures return the byte +position where the next I/O operation would take place in the file +attached to the given port (relative to the beginning of the +file). When called with two or three arguments, the byte position for +subsequent I/O operations on the given port is changed to +position, which must be an exact integer. When whence is +omitted or is 0, the position is relative to the beginning of +the file. When whence is 1, the position is relative to +the current byte position of the file. When whence is 2, the +position is relative to the end of the file. The return value +is the new byte position. On most operating systems the byte position +for reading and writing of a given bidirectional port are the same. +

+

When input-port-byte-position is called to change the byte +position of an input-port, all input buffers will be flushed so that +the next byte read will be the one at the given position. +

+

When output-port-byte-position is called to change the byte +position of an output-port, there is an implicit call to +force-output before the position is changed. +

+

For example: +

+
 
> (define p  ; p is an input-output-port
+    (open-file '(path: "test" char-encoding: ISO-8859-1 create: maybe)))
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(0 0)
+> (display "abcdefghij\n" p)
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(0 0)
+> (force-output p)
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(11 11)
+> (input-port-byte-position p 2)
+2
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(2 2)
+> (peek-char p)
+#\c
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(11 11)
+> (output-port-byte-position p -7 2)
+4
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(4 4)
+> (write-char #\! p)
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(4 4)
+> (force-output p)
+> (list (input-port-byte-position p) (output-port-byte-position p))
+(5 5)
+> (input-port-byte-position p 1)
+1
+> (read p)
+bcd!fghij
+
+ + + +
+ + + + + + + + + + + +
Back: 17.7.1 Filesystem devicesForward: 17.7.3 Network devices   FastBack: 17. I/O and portsUp: 17.7 Device-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.7.2 Process devices

+ +
(open-process path-or-settings)procedure
+
(open-input-process path-or-settings)procedure
+
(open-output-process path-or-settings)procedure
+
(call-with-input-process path-or-settings proc)procedure
+
(call-with-output-process path-or-settings proc)procedure
+
(with-input-from-process path-or-settings thunk)procedure
+
(with-output-to-process path-or-settings thunk)procedure
+ +

All of these procedures start a new operating system process and +create a bidirectional port which allows communication with that +process on its standard input and standard output. The +direction: setting will default to the value input for +the procedures open-input-process, +call-with-input-process and with-input-from-process, to +the value output for the procedures open-output-process, +call-with-output-process and with-output-to-process, and +to the value input-output for the procedure +open-process. If the direction: setting is +input, the output-port side is closed. If the +direction: setting is output, the input-port side is +closed. +

+

The procedures open-process, open-input-process and +open-output-process return the port that is created. The +procedures call-with-input-process and +call-with-output-process call the procedure proc with the +port as single argument, and then return the value(s) of this call +after closing the port and waiting for the process to terminate. The +procedures with-input-from-process and +with-output-to-process dynamically bind the current input-port +and current output-port respectively to the port created for the +duration of a call to the procedure thunk with no argument. The +value(s) of the call to thunk are returned after closing the +port and waiting for the process to terminate. +

+

The first argument of this procedure is either a string denoting a +filesystem path of an executable program or a list of port settings +which must contain a path: setting. Here are the settings +allowed in addition to the generic settings of byte-ports: +

+ + +

For example: +

+
 
> (with-input-from-process "date" read-line)
+"Sun Jun 14 15:06:41 EDT 2009"
+> (define p (open-process (list path: "ls"
+                                arguments: '("../examples"))))
+> (read-line p)
+"README"
+> (read-line p)
+"Xlib-simple"
+> (close-port p)
+> (define p (open-process "/usr/bin/dc"))
+> (display "2 100 ^ p\n" p)
+> (force-output p)
+> (read-line p)
+"1267650600228229401496703205376"
+
+ + + +
(process-pid process-port)procedure
+ +

This procedure returns the PID (Process Identifier) of the process of +process-port. The PID is a small exact integer. +

+

For example: +

+
 
> (let ((p (open-process "sort")))
+    (process-pid p))
+318
+
+ + + +
(process-status process-port [timeout [timeout-val]])procedure
+ +

This procedure causes the current thread to wait until the process of +process-port terminates (normally or not) or until the timeout +is reached if timeout is supplied. If the timeout is reached, +process-status returns timeout-val if it is supplied, +otherwise an unterminated-process-exception object is raised. The +procedure returns the process exit status as encoded by the operating +system. Typically, if the process exited normally the return value is +the process exit status multiplied by 256. +

+

For example: +

+
 
> (let ((p (open-process "sort")))
+    (for-each (lambda (x) (pretty-print x p))
+              '(22 11 33))
+    (close-output-port p)
+    (let ((r (read-all p)))
+      (close-input-port p)
+      (list (process-status p) r)))
+(0 (11 22 33))
+
+ + + +
(unterminated-process-exception? obj)procedure
+
(unterminated-process-exception-procedure exc)procedure
+
(unterminated-process-exception-arguments exc)procedure
+ +

Unterminated-process-exception objects are raised when a call to the +process-status procedure reaches its timeout before the target +process terminates and a timeout-value parameter is not specified. +The parameter exc must be an unterminated-process-exception +object. +

+

The procedure unterminated-process-exception? returns +#t when obj is an unterminated-process-exception +object and #f otherwise. +

+

The procedure unterminated-process-exception-procedure +returns the procedure that raised exc. +

+

The procedure unterminated-process-exception-arguments +returns the list of arguments of the procedure that raised exc. +

+

For example: +

+
 
> (define (handler exc)
+    (if (unterminated-process-exception? exc)
+        (list (unterminated-process-exception-procedure exc)
+              (unterminated-process-exception-arguments exc))
+        'not-unterminated-process-exception))
+> (with-exception-catcher
+    handler
+    (lambda ()
+      (let ((p (open-process "sort")))
+        (process-status p 1))))
+(#<procedure #2 process-status> (#<input-output-port #3 (process "sort")>))
+
+ + + +
+ + + + + + + + + + + +
Back: 17.7.2 Process devicesForward: 17.8 Directory-ports   FastBack: 17. I/O and portsUp: 17.7 Device-portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.7.3 Network devices

+ +
(open-tcp-client port-number-or-address-or-settings)procedure
+ +

This procedure opens a network connection to a socket server and +returns a tcp-client-port (a subtype of device-port) that represents +this connection and allows communication with that server. The +default value of the direction: setting is input-output, +i.e. the Scheme program can send information to the server and receive +information from the server. The sending direction can be +“shutdown” using the close-output-port procedure and the +receiving direction can be “shutdown” using the +close-input-port procedure. The close-port procedure +closes both directions of the connection. +

+

The parameter of this procedure is an IP port number (16-bit nonnegative +exact integer), a string of the form "HOST:PORT" or +a list of port settings. When the parameter is the number PORT +it is handled as if it was the setting port-number: PORT. +When the parameter is the string "HOST:PORT" it is +handled as if it was the setting server-address: +"HOST:PORT". +

+

Here are the settings allowed in addition to the generic settings of +byte-ports: +

+ + +

Below is an example of the client-side code that opens a connection to +an HTTP server on port 8080 of the loopback interface (with IP address +127.0.0.1). For the server-side code see the example for the +procedure open-tcp-server. +

+
 
> (define p (open-tcp-client (list port-number: 8080
+                                   eol-encoding: 'cr-lf)))
+> p
+#<input-output-port #2 (tcp-client #u8(127 0 0 1) 8080)>
+> (display "GET /\n" p)
+> (force-output p)
+> (read-line p)
+"<HTML>"
+
+ + + +
(open-tcp-server port-number-or-address-or-settings)procedure
+ +

This procedure sets up a socket to accept network connection requests +from clients and returns a tcp-server-port from which network +connections to clients are obtained. Tcp-server-ports are a direct +subtype of object-ports (i.e. they are not character-ports) and are +input-ports. Reading from a tcp-server-port with the read +procedure will block until a network connection request is received +from a client. The read procedure will then return a +tcp-client-port (a subtype of device-port) that represents this +connection and allows communication with that client. Closing a +tcp-server-port with either the close-input-port or +close-port procedures will cause the network subsystem to stop +accepting connections on that socket. +

+

The parameter of this procedure is an IP port number (16-bit nonnegative +exact integer), a string of the form "INTF:PORT" or +a list of port settings which must contain a port-number: +setting. When the parameter is the number PORT it is handled as +if it was the setting port-number: PORT. When the +parameter is the string "INTF:PORT" it is handled +as if it was the setting server-address: +"INTF:PORT". +

+

Below is a list of the settings allowed in addition to the settings +keep-alive: and coalesce: allowed by the +open-tcp-client procedure and the generic settings of +byte-ports. The settings which are not listed below apply to the +tcp-client-port that is returned by read when a connection is +accepted and have the same meaning as if they were used in a call to +the open-tcp-client procedure. +

+ + +

Below is an example of the server-side code that accepts connections +on port 8080 of any network interface. For the client-side code see +the example for the procedure open-tcp-client. +

+
 
> (define s (open-tcp-server (list server-address: "*"
+                                   port-number: 8080
+                                   eol-encoding: 'cr-lf)))
+> (define p (read s))  ; blocks until client connects
+> p
+#<input-output-port #2 (tcp-client 8080)>
+> (read-line p)
+"GET /"
+> (display "<HTML>\n" p)
+> (force-output p)
+
+ + + +
(tcp-service-register! port-number-or-address-or-settings thunk [thread-group])procedure
+
(tcp-service-unregister! port-number-or-address-or-settings)procedure
+ +

The procedure tcp-service-register! sets up a socket to accept +network connection requests from clients and creates a “service” +thread which processes the incoming connections. The parameter +port-number-or-address-or-settings has the same meaning as for +the procedure open-tcp-server. +

+

For each connection established the service thread creates a +“handler” thread which executes a call to the procedure thunk +with no argument. The handler thread’s current input-port and current +output-port are both set to the tcp-client-port created for the +connection. There is no need for the thunk to close the +tcp-client-port, as this is done by the handler thread when the +thunk returns normally. +

+

The procedure tcp-service-unregister! terminates the service +thread which was registered by tcp-service-register! with the +same network interface and port number (if a service thread is still +registered). The procedure tcp-service-register! implicitly +calls tcp-service-unregister! before registering the new +service thread. +

+
 
> (tcp-service-register!
+   8000
+   (lambda () (display "hello\n")))
+> (define p (open-tcp-client 8000))
+> (read-line p)
+"hello"
+> (tcp-service-unregister! 8000)
+
+ + + +
+ + + + + + + + + + + +
Back: 17.7.3 Network devicesForward: 17.9 Vector-ports   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.8 Directory-ports

+ +
(open-directory path-or-settings)procedure
+ +

This procedure opens a directory of the filesystem for reading its +entries and returns a directory-port from which the entries can be +enumerated. Directory-ports are a direct subtype of object-ports +(i.e. they are not character-ports) and are input-ports. Reading from +a directory-port with the read procedure returns the next file +name in the directory as a string. The end-of-file object is returned +when all the file names have been enumerated. Another way to get the +list of all files in a directory is the directory-files +procedure which returns a list of the files in the directory. The +advantage of using directory-ports is that it allows iterating over +the files in a directory in constant space, which is interesting when +the number of files in the directory is not known in advance and may +be large. Note that the order in which the names are returned is +operating-system dependent. +

+

The parameter of this procedure is either a string denoting a +filesystem path to a directory or a list of port settings which must +contain a path: setting. Here are the settings allowed in +addition to the generic settings of object-ports: +

+ + +

For example: +

+
 
> (let ((p (open-directory (list path: "../examples"
+                                 ignore-hidden: #f))))
+    (let loop ()
+      (let ((fn (read p)))
+        (if (string? fn)
+            (begin
+              (pp (path-expand fn))
+              (loop)))))
+    (close-input-port p))
+"/u/feeley/examples/."
+"/u/feeley/examples/.."
+"/u/feeley/examples/complex"
+"/u/feeley/examples/README"
+"/u/feeley/examples/simple"
+> (define x (open-directory "../examples"))
+> (read-all x)
+("complex" "README" "simple")
+
+ + + +
+ + + + + + + + + + + +
Back: 17.8 Directory-portsForward: 17.10 String-ports   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.9 Vector-ports

+ +
(open-vector [vector-or-settings])procedure
+
(open-input-vector [vector-or-settings])procedure
+
(open-output-vector [vector-or-settings])procedure
+
(call-with-input-vector vector-or-settings proc)procedure
+
(call-with-output-vector vector-or-settings proc)procedure
+
(with-input-from-vector vector-or-settings thunk)procedure
+
(with-output-to-vector vector-or-settings thunk)procedure
+ +

Vector-ports represent streams of Scheme objects. They are a direct +subtype of object-ports (i.e. they are not character-ports). All of +these procedures create vector-ports that are either unidirectional or +bidirectional. The direction: setting will default to the +value input for the procedures open-input-vector, +call-with-input-vector and with-input-from-vector, to +the value output for the procedures open-output-vector, +call-with-output-vector and with-output-to-vector, and +to the value input-output for the procedure open-vector. +Bidirectional vector-ports behave like FIFOs: data written to the port +is added to the end of the stream that is read. It is only when a +bidirectional vector-port’s output-side is closed with a call to the +close-output-port procedure that the stream’s end is known +(when the stream’s end is reached, reading the port returns the +end-of-file object). +

+

The procedures open-vector, open-input-vector and +open-output-vector return the port that is created. The +procedures call-with-input-vector and +call-with-output-vector create a vector port, call the +procedure proc with the port as single argument and then close +the port. The procedures with-input-from-vector and +with-output-to-vector create a vector port, dynamically bind +the current input-port and current output-port respectively to the +port created for the duration of a call to the procedure thunk +with no argument, and then close the port. The procedures +call-with-input-vector and with-input-from-vector return +the value returned by the procedures proc and thunk +respectively. The procedures call-with-output-vector and +with-output-to-vector return the vector accumulated in the port +(see get-output-vector). +

+

The first parameter of these procedures is either a vector of the +elements used to initialize the stream or a list of port settings. If +it is not specified, the parameter of the open-vector, +open-input-vector, and open-output-vector procedures +defaults to an empty list of port settings. Here are the settings +allowed in addition to the generic settings of object-ports: +

+ + +

For example: +

+
 
> (define p (open-vector))
+> (write 1 p)
+> (write 2 p)
+> (write 3 p)
+> (force-output p)
+> (read p)
+1
+> (read p)
+2
+> (close-output-port p)
+> (read p)
+3
+> (read p)
+#!eof
+> (with-output-to-vector '() (lambda () (write 1) (write 2)))
+#(1 2)
+
+ + + +
(open-vector-pipe [vector-or-settings1 [vector-or-settings2]])procedure
+ +

The procedure open-vector-pipe creates two vector-ports and +returns these two ports. The two ports are interrelated as follows: +the first port’s output-side is connected to the second port’s +input-side and the first port’s input-side is connected to the second +port’s output-side. The value vector-or-settings1 is used to +setup the first vector-port and vector-or-settings2 is used to +setup the second vector-port. The same settings as for +open-vector are allowed. The default direction: setting +is input-output (i.e. a bidirectional port is created). If it +is not specified vector-or-settings1 defaults to the empty list. +If it is not specified vector-or-settings2 defaults to +vector-or-settings1 but with the init: setting set to the +empty vector and with the input and output settings exchanged (e.g. if +the first port is an input-port then the second port is an +output-port, if the first port’s input-side is non-buffered then the +second port’s output-side is non-buffered). +

+

For example: +

+
 
> (define (server op)
+    (receive (c s) (open-vector-pipe)  ; client-side and server-side ports
+      (thread-start!
+        (make-thread
+          (lambda ()
+            (let loop ()
+              (let ((request (read s)))
+                (if (not (eof-object? request))
+                    (begin
+                      (write (op request) s)
+                      (newline s)
+                      (force-output s)
+                      (loop))))))))
+      c))
+> (define a (server (lambda (x) (expt 2 x))))
+> (define b (server (lambda (x) (expt 10 x))))
+> (write 100 a)
+> (write 30 b)
+> (read a)
+1267650600228229401496703205376
+> (read b)
+1000000000000000000000000000000
+
+ + + +
(get-output-vector vector-port)procedure
+ +

The procedure get-output-vector takes an output vector-port or +a bidirectional vector-port as parameter and removes all the objects +currently on the output-side, returning them in a vector. The port +remains open and subsequent output to the port and calls to the +procedure get-output-vector are possible. +

+

For example: +

+
 
> (define p (open-vector '#(1 2 3)))
+> (write 4 p)
+> (get-output-vector p)
+#(1 2 3 4)
+> (write 5 p)
+> (write 6 p)
+> (get-output-vector p)
+#(5 6)
+
+ + + +
+ + + + + + + + + + + +
Back: 17.9 Vector-portsForward: 17.11 U8vector-ports   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.10 String-ports

+ +
(open-string [string-or-settings])procedure
+
(open-input-string [string-or-settings])procedure
+
(open-output-string [string-or-settings])procedure
+
(call-with-input-string string-or-settings proc)procedure
+
(call-with-output-string string-or-settings proc)procedure
+
(with-input-from-string string-or-settings thunk)procedure
+
(with-output-to-string string-or-settings thunk)procedure
+
(open-string-pipe [string-or-settings1 [string-or-settings2]])procedure
+
(get-output-string string-port)procedure
+ +

String-ports represent streams of characters. They are a direct +subtype of character-ports. These procedures are the string-port +analog of the procedures specified in the vector-ports section. Note +that these procedures are a superset of the procedures specified in +the “Basic String Ports SRFI” (SRFI 6). +

+

For example: +

+
 
> (define p (open-string))
+> (write 1 p)
+> (write 2 p)
+> (write 3 p)
+> (force-output p)
+> (read-char p)
+#\1
+> (read-char p)
+#\2
+> (close-output-port p)
+> (read-char p)
+#\3
+> (read-char p)
+#!eof
+> (with-output-to-string '() (lambda () (write 1) (write 2)))
+"12"
+
+ + + +
(object->string obj [n])procedure
+ +

This procedure converts the object obj to its external +representation and returns it in a string. The parameter n +specifies the maximal width of the resulting string. If the external +representation is wider than n, the resulting string will be +truncated to n characters and the last 3 characters will be set +to periods. Note that the current readtable is used. +

+

For example: +

+
 
> (object->string (expt 2 100))
+"1267650600228229401496703205376"
+> (object->string (expt 2 100) 30)
+"126765060022822940149670320..."
+> (object->string (cons car cdr))
+"(#<procedure #2 car> . #<procedure #3 cdr>)"
+
+ + + +
+ + + + + + + + + + + +
Back: 17.10 String-portsForward: 17.12 Other procedures related to I/O   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.11 U8vector-ports

+ +
(open-u8vector [u8vector-or-settings])procedure
+
(open-input-u8vector [u8vector-or-settings])procedure
+
(open-output-u8vector [u8vector-or-settings])procedure
+
(call-with-input-u8vector u8vector-or-settings proc)procedure
+
(call-with-output-u8vector u8vector-or-settings proc)procedure
+
(with-input-from-u8vector u8vector-or-settings thunk)procedure
+
(with-output-to-u8vector u8vector-or-settings thunk)procedure
+
(open-u8vector-pipe [u8vector-or-settings1 [u8vector-or-settings2]])procedure
+
(get-output-u8vector u8vector-port)procedure
+ +

U8vector-ports represent streams of bytes. They are a direct subtype +of byte-ports. These procedures are the u8vector-port analog of the +procedures specified in the vector-ports section. +

+

For example: +

+
 
> (define p (open-u8vector))
+> (write 1 p)
+> (write 2 p)
+> (write 3 p)
+> (force-output p)
+> (read-u8 p)
+49
+> (read-u8 p)
+50
+> (close-output-port p)
+> (read-u8 p)
+51
+> (read-u8 p)
+#!eof
+> (with-output-to-u8vector '() (lambda () (write 1) (write 2)))
+#u8(49 50)
+
+ + + +
+ + + + + + + + + + + +
Back: 17.11 U8vector-portsForward: 18. Lexical syntax and readtables   FastBack: 17. I/O and portsUp: 17. I/O and portsFastForward: 18. Lexical syntax and readtablesTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

17.12 Other procedures related to I/O

+ +
(current-input-port [new-value])procedure
+
(current-output-port [new-value])procedure
+
(current-error-port [new-value])procedure
+
(current-readtable [new-value])procedure
+ +

These procedures are parameter objects which represent respectively: +the current input-port, the current output-port, the current +error-port, and the current readtable. +

+ + +
(print [port: port] obj)procedure
+
(println [port: port] obj)procedure
+ +

The print procedure writes a representation of each obj, +from left to right, to port. When a compound object is +encountered (pair, list, vector, box) the elements of that object are +recursively written without the surrounding tokens (parentheses, +spaces, dots, etc). Strings, symbols, keywords and characters are +written like the display procedure. If there are more than one +obj, the first obj must not be a keyword object. If it is +not specified, port defaults to the current output-port. The +procedure print returns an unspecified value. +

+

The println procedure does the same thing as the print +procedure and then writes an end of line to port. +

+

For example: +

+
 
> (println "2*2 is " (* 2 2) " and 2+2 is " (+ 2 2))
+2*2 is 4 and 2+2 is 4
+> (define x (list "<i>" (list "<tt>" 123 "</tt>") "</i>"))
+> (println x)
+<i><tt>123</tt></i>
+> (define p (open-output-string))
+> (print port: p 1 #\2 "345")
+> (get-output-string p)
+"12345"
+
+ + + +
+ + + + + + + + + + + +
Back: 17.12 Other procedures related to I/OForward: 18.1 Readtables   FastBack: 17. I/O and portsUp: Gambit-CFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18. Lexical syntax and readtables

+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 18. Lexical syntax and readtablesForward: 18.2 Boolean syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.1 Readtables

+ +

Readtables control the external textual representation of Scheme +objects, that is the encoding of Scheme objects using characters. +Readtables affect the behavior of the reader (i.e. the read +procedure and the parser used by the load procedure and the +interpreter and compiler) and the printer (i.e. the procedures +write, display, print, println, +pretty-print, and pp, and the procedure used by the REPL +to print results). To preserve write/read invariance the printer and +reader must be using compatible readtables. For example a symbol +which contains upper case letters will be printed with special escapes +if the readtable indicates that the reader is case-insensitive. +

+

Readtables are immutable records whose fields specify various textual +representation aspects. There are accessor procedures to retrieve the +content of specific fields. There are also functional update +procedures that create a copy of a readtable, with a specific field +set to a new value. +

+
(readtable? obj)procedure
+ +

This procedure returns #t when obj is a readtable and +#f otherwise. +

+

For example: +

+
 
> (readtable? (current-readtable))
+#t
+> (readtable? 123)
+#f
+
+ + + +
(readtable-case-conversion? readtable)procedure
+
(readtable-case-conversion?-set readtable new-value)procedure
+ +

The procedure readtable-case-conversion? returns the content of +the case-conversion? field of readtable. When the +content of this field is #f, the reader preserves the case of +symbols and keyword objects that are read (i.e. Ice and +ice are distinct symbols). When the content of this field is +the symbol upcase, the reader converts lowercase letters to +uppercase when reading symbols and keywords (i.e. Ice is read +as the symbol (string->symbol "ICE")). Otherwise the reader +converts uppercase letters to lowercase when reading symbols and +keywords (i.e. Ice is read as the symbol (string->symbol +"ice")). +

+

The procedure readtable-case-conversion?-set returns a copy +of readtable where only the case-conversion? field +has been changed to new-value. +

+

For example: +

+
 
> (output-port-readtable-set!
+    (repl-output-port)
+    (readtable-case-conversion?-set
+      (output-port-readtable (repl-output-port))
+      #f))
+> (input-port-readtable-set!
+    (repl-input-port)
+    (readtable-case-conversion?-set
+      (input-port-readtable (repl-input-port))
+      #f))
+> 'Ice
+Ice
+> (input-port-readtable-set!
+    (repl-input-port)
+    (readtable-case-conversion?-set
+      (input-port-readtable (repl-input-port))
+      #t))
+> 'Ice
+ice
+> (input-port-readtable-set!
+    (repl-input-port)
+    (readtable-case-conversion?-set
+      (input-port-readtable (repl-input-port))
+      'upcase))
+> 'Ice
+ICE
+
+ + + +
(readtable-keywords-allowed? readtable)procedure
+
(readtable-keywords-allowed?-set readtable new-value)procedure
+ +

The procedure readtable-keywords-allowed? returns the content +of the keywords-allowed? field of readtable. When the +content of this field is #f, the reader does not recognize +keyword objects (i.e. :foo and foo: are read as the +symbols (string->symbol ":foo") and (string->symbol +"foo:") respectively). When the content of this field is the symbol +prefix, the reader recognizes keyword objects that start with a +colon, as in Common Lisp (i.e. :foo is read as the keyword +(string->keyword "foo")). Otherwise the reader recognizes +keyword objects that end with a colon, as in DSSSL (i.e. foo: +is read as the symbol (string->symbol "foo")). +

+

The procedure readtable-keywords-allowed?-set returns a copy +of readtable where only the keywords-allowed? field +has been changed to new-value. +

+

For example: +

+
 
> (input-port-readtable-set!
+    (repl-input-port)
+    (readtable-keywords-allowed?-set
+      (input-port-readtable (repl-input-port))
+      #f))
+> (map keyword? '(foo :foo foo:))
+(#f #f #f)
+> (input-port-readtable-set!
+    (repl-input-port)
+    (readtable-keywords-allowed?-set
+      (input-port-readtable (repl-input-port))
+      #t))
+> (map keyword? '(foo :foo foo:))
+(#f #f #t)
+> (input-port-readtable-set!
+    (repl-input-port)
+    (readtable-keywords-allowed?-set
+      (input-port-readtable (repl-input-port))
+      'prefix))
+> (map keyword? '(foo :foo foo:))
+(#f #t #f)
+
+ + + +
(readtable-sharing-allowed? readtable)procedure
+
(readtable-sharing-allowed?-set readtable new-value)procedure
+ + + +

The procedure readtable-sharing-allowed? returns the content of +the sharing-allowed? field of readtable. The reader +recognizes the #n# and #n=datum +notation for circular structures and the printer uses this notation if +and only if the content of the sharing-allowed? field is not +#f. Moreover when the content of the sharing-allowed? +field is the symbol serialize, the printer uses a special +external representation that the reader understands and that extends +write/read invariance to the following types: records, procedures and +continuations. Note that an object can be serialized and deserialized +if and only if all of its components are serializable. +

+

The procedure readtable-sharing-allowed?-set returns a copy +of readtable where only the sharing-allowed? field +has been changed to new-value. +

+

Here is a simple example: +

+
 
> (define (wr obj allow?)
+    (call-with-output-string
+      '()
+      (lambda (p)
+        (output-port-readtable-set!
+          p
+          (readtable-sharing-allowed?-set
+            (output-port-readtable p)
+            allow?))
+        (write obj p))))
+> (define (rd str allow?)
+    (call-with-input-string
+      str
+      (lambda (p)
+        (input-port-readtable-set!
+          p
+          (readtable-sharing-allowed?-set
+            (input-port-readtable p)
+            allow?))
+        (read p))))
+> (define x (list 1 2 3))
+> (set-car! (cdr x) (cddr x))
+> (wr x #f)
+"(1 (3) 3)"
+> (wr x #t)
+"(1 #0=(3) . #0#)"
+> (define y (rd (wr x #t) #t))
+> y
+(1 (3) 3)
+> (eq? (cadr y) (cddr y))
+#t
+> (define f #f)
+> (let ((free (expt 2 10)))
+  (set! f (lambda (x) (+ x free))))
+> (define s (wr f 'serialize))
+> (string-length s)
+4196
+> (define g (rd s 'serialize))
+> (eq? f g)
+#f
+> (g 4)
+1028
+
+ +

Continuations are tricky to serialize because they contain a dynamic +environment and this dynamic environment may contain non-serializable +objects, in particular ports attached to operating-system streams such +as files, the console or standard input/output. Indeed, all dynamic +environments contain a binding for the current-input-port and +current-output-port. Moreover, any thread that has started a +REPL has a continuation which refers to the repl-context object +in its dynamic environment. A repl-context object contains the +interaction channel, which is typically connected to a +non-serializable port, such as the console. Another problem is that +the parameterize form saves the old binding of the parameter in +the continuation, so it is not possible to eliminate the references to +these ports in the continuation by using the parameterize form +alone. +

+

Serialization of continuations can be achieved dependably by taking +advantage of string-ports, which are serializable objects (unless +there is a blocked thread), and the following features of threads: +they inherit the dynamic environment of the parent thread and they +start with an initial continuation that contains only serializable +objects. So a thread created in a dynamic environment where +current-input-port and current-output-port are bound to +a dummy string-port has a serializable continuation. +

+

Here is an example where continuations are serialized: +

+
 
> (define (wr obj)
+    (call-with-output-string
+     '()
+     (lambda (p)
+       (output-port-readtable-set!
+        p
+        (readtable-sharing-allowed?-set
+         (output-port-readtable p)
+         'serialize))
+       (write obj p))))
+> (define (rd str)
+    (call-with-input-string
+     str
+     (lambda (p)
+       (input-port-readtable-set!
+        p
+        (readtable-sharing-allowed?-set
+         (input-port-readtable p)
+         'serialize))
+       (read p))))
+> (define fifo (open-vector))
+> (define (suspend-and-die!)
+    (call-with-current-continuation
+     (lambda (k)
+       (write (wr k) fifo)
+       (newline fifo)
+       (force-output fifo)
+       (thread-terminate! (current-thread)))))
+> (let ((dummy-port (open-string)))
+    (parameterize ((current-input-port dummy-port)
+                   (current-output-port dummy-port))
+      (thread-start!
+       (make-thread
+        (lambda ()
+          (* 100
+             (suspend-and-die!)))))))
+#<thread #2>
+> (define s (read fifo))
+> (thread-join!
+    (thread-start!
+      (make-thread
+        (lambda ()
+          ((rd s) 111)))))
+11100
+> (thread-join!
+    (thread-start!
+      (make-thread
+        (lambda ()
+          ((rd s) 222)))))
+22200
+> (string-length s)
+13114
+
+ + + +
(readtable-eval-allowed? readtable)procedure
+
(readtable-eval-allowed?-set readtable new-value)procedure
+ +

The procedure readtable-eval-allowed? returns the content of +the eval-allowed? field of readtable. The reader +recognizes the #.expression notation for read-time +evaluation if and only if the content of the eval-allowed? +field is not #f. +

+

The procedure readtable-eval-allowed?-set returns a copy +of readtable where only the eval-allowed? field +has been changed to new-value. +

+

For example: +

+
 
> (input-port-readtable-set!
+    (repl-input-port)
+    (readtable-eval-allowed?-set
+      (input-port-readtable (repl-input-port))
+      #t))
+> '(5 plus 7 is #.(+ 5 7))
+(5 plus 7 is 12)
+> '(buf = #.(make-u8vector 25))
+(buf = #u8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
+
+ + + +
(readtable-write-cdr-read-macros? readtable)procedure
+
(readtable-write-cdr-read-macros?-set readtable new-value)procedure
+
(readtable-write-extended-read-macros? readtable)procedure
+
(readtable-write-extended-read-macros?-set readtable new-value)procedure
+ +

The procedure readtable-write-cdr-read-macros? returns the +content of the write-cdr-read-macros? field of readtable. +The procedure readtable-write-extended-read-macros? returns the +content of the write-extended-read-macros? field of +readtable. +

+

At all times the printer uses read-macros in its output for datums of +the form (quote datum), (quasiquote datum), +(unquote datum), and (unquote-splicing +datum). That is the following read-macro notations will be +used respectively: 'datum, `datum, +,datum, and ,@datum. Moreover, normally +the read-macros will not be used when the form appears in the cdr of a +list, for example (foo quote bar), (foo . (quote bar)) +and (foo . 'bar) will all be printed as (foo quote bar). +

+

When the content of the write-cdr-read-macros? field is not +#f, the printer will use read-macros when the forms appear in +the cdr of a list. For example (foo quote bar) will be printed +as (foo . 'bar). When the content of the +write-extended-read-macros? field is not #f, the printer +will also use extended read-macros, for example #'datum +in place of (syntax datum). +

+

The procedure readtable-write-cdr-read-macros?-set returns a +copy of readtable where only the write-cdr-read-macros? +field has been changed to new-value. The procedure +readtable-write-extended-read-macros?-set returns a copy of +readtable where only the write-extended-read-macros? +field has been changed to new-value. +

+

For example: +

+
 
> (output-port-readtable-set!
+    (repl-output-port)
+    (readtable-write-extended-read-macros?-set
+      (output-port-readtable (repl-output-port))
+      #t))
+> '(foo (syntax bar))
+(foo #'bar)
+> '(foo syntax bar)
+(foo syntax bar)
+> (output-port-readtable-set!
+    (repl-output-port)
+    (readtable-write-cdr-read-macros?-set
+      (output-port-readtable (repl-output-port))
+      #t))
+> '(foo syntax bar)
+(foo . #'bar)
+
+ + + +
(readtable-max-write-level readtable)procedure
+
(readtable-max-write-level-set readtable new-value)procedure
+ +

The procedure readtable-max-write-level returns the content of +the max-write-level field of readtable. The printer will +display an ellipsis for the elements of lists and vectors that are +nested deeper than this level. +

+

The procedure readtable-max-write-level-set returns a copy +of readtable where only the max-write-level field +has been changed to new-value, which must be an nonnegative +fixnum. +

+

For example: +

+
 
> (define (wr obj n)
+    (call-with-output-string
+      '()
+      (lambda (p)
+        (output-port-readtable-set!
+          p
+          (readtable-max-write-level-set
+            (output-port-readtable p)
+            n))
+        (write obj p))))
+> (wr '(a #(b (c c) #u8(9 9 9) b) a) 3)
+"(a #(b (c c) #u8(9 9 9) b) a)"
+> (wr '(a #(b (c c) #u8(9 9 9) b) a) 2)
+"(a #(b (...) #u8(...) b) a)"
+> (wr '(a #(b (c c) #u8(9 9 9) b) a) 1)
+"(a #(...) a)"
+> (wr '(a #(b (c c) #u8(9 9 9) b) a) 0)
+"(...)"
+> (wr 'hello 0)
+"hello"
+
+ + + +
(readtable-max-write-length readtable)procedure
+
(readtable-max-write-length-set readtable new-value)procedure
+

The procedure readtable-max-write-length returns the content of +the max-write-length field of readtable. The printer will +display an ellipsis for the elements of lists and vectors that are at +an index beyond that length. +

+

The procedure readtable-max-write-length-set returns a copy +of readtable where only the max-write-length field +has been changed to new-value, which must be an nonnegative +fixnum. +

+

For example: +

+
 
> (define (wr obj n)
+    (call-with-output-string
+      '()
+      (lambda (p)
+        (output-port-readtable-set!
+          p
+          (readtable-max-write-length-set
+            (output-port-readtable p)
+            n))
+        (write obj p))))
+> (wr '(a #(b (c c) #u8(9 9 9) b) . a) 4)
+"(a #(b (c c) #u8(9 9 9) b) . a)"
+> (wr '(a #(b (c c) #u8(9 9 9) b) . a) 3)
+"(a #(b (c c) #u8(9 9 9) ...) . a)"
+> (wr '(a #(b (c c) #u8(9 9 9) b) . a) 2)
+"(a #(b (c c) ...) . a)"
+> (wr '(a #(b (c c) #u8(9 9 9) b) . a) 1)
+"(a ...)"
+> (wr '(a #(b (c c) #u8(9 9 9) b) . a) 0)
+"(...)"
+
+ + + +
(readtable-max-unescaped-char readtable)procedure
+
(readtable-max-unescaped-char-set readtable new-value)procedure
+ +

The procedure readtable-max-unescaped-char returns the content +of the max-unescaped-char field of readtable. The +printer will display using an escape sequence any character within +symbols, strings and character objects greater than +max-unescaped-char +

+

The procedure readtable-max-unescaped-char-set returns a copy +of readtable where only the max-unescaped-char field +has been changed to new-value, which must be a character. +

+

For example: +

+
 
> (define rt (output-port-readtable (repl-output-port)))
+> (readtable-max-unescaped-char rt)
+#\delete
+> (string (integer->char 233))
+"\351"
+> (define (f c)
+    (with-output-to-string
+     (list readtable: (readtable-max-unescaped-char-set rt c))
+     (lambda () (write (string (integer->char 233))))))
+> (f #\delete)
+"\"\\351\""
+> (string-length (f #\delete))
+6
+> (f #\U0010ffff)
+"\"\351\""
+> (string-length (f #\U0010ffff))
+3
+> (output-port-readtable-set!
+   (repl-output-port)
+   (readtable-max-unescaped-char-set rt #\U0010ffff))
+> (string (integer->char 233))
+"é"
+
+ + + +
(readtable-start-syntax readtable)procedure
+
(readtable-start-syntax-set readtable new-value)procedure
+ +

The procedure readtable-start-syntax returns the content of the +start-syntax field of readtable. The reader uses this +field to determine in which syntax to start parsing the input. When +the content of this field is the symbol six, the reader starts +in the infix syntax. Otherwise the reader starts in the prefix +syntax. +

+

The procedure readtable-start-syntax-set returns a copy +of readtable where only the start-syntax field +has been changed to new-value. +

+

For example: +

+
 
> (+ 2 3)
+5
+> (input-port-readtable-set!
+   (repl-input-port)
+   (readtable-start-syntax-set
+     (input-port-readtable (repl-input-port))
+     'six))
+> 2+3;
+5
+> exit();
+
+ + + +
+ + + + + + + + + + + +
Back: 18.1 ReadtablesForward: 18.3 Character syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.2 Boolean syntax

+ +

Booleans are required to be followed by a delimiter +(i.e. #f64() is not the boolean #f followed by the +number 64 and the empty list). +

+
+ + + + + + + + + + + +
Back: 18.2 Boolean syntaxForward: 18.4 String syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.3 Character syntax

+ +

Characters are required to be followed by a delimiter +(i.e. #\spaceballs is not the character #\space followed +by the symbol balls). The lexical syntax of characters is +extended to allow the following: +

+
+
#\nul
+

Unicode character 0 +

+
#\alarm
+

Unicode character 7 +

+
#\backspace
+

Unicode character 8 +

+
#\tab
+

Unicode character 9 +

+
#\newline
+

Unicode character 10 (newline character) +

+
#\linefeed
+

Unicode character 10 +

+
#\vtab
+

Unicode character 11 +

+
#\page
+

Unicode character 12 +

+
#\return
+

Unicode character 13 +

+
#\esc
+

Unicode character 27 +

+
#\space
+

Unicode character 32 (space character) +

+
#\delete
+

Unicode character 127 +

+
#\xhh
+

character encoded in hexadecimal (>= 1 hexadecimal digit) +

+
#\uhhhh
+

character encoded in hexadecimal (exactly 4 hexadecimal digits) +

+
#\Uhhhhhhhh
+

character encoded in hexadecimal (exactly 8 hexadecimal digits) +

+
+ +
+ + + + + + + + + + + +
Back: 18.3 Character syntaxForward: 18.5 Symbol syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.4 String syntax

+ +

The lexical syntax of quoted strings is extended to allow the following +escape codes: +

+
+
\a
+

Unicode character 7 +

+
\b
+

Unicode character 8 +

+
\t
+

Unicode character 9 +

+
\n
+

Unicode character 10 (newline character) +

+
\v
+

Unicode character 11 +

+
\f
+

Unicode character 12 +

+
\r
+

Unicode character 13 +

+
\"
+

" +

+
\\
+

\ +

+
\|
+

| +

+
\?
+

? +

+
\ooo
+

character encoded in octal (1 to 3 octal digits, first digit must be less +than 4 when there are 3 octal digits) +

+
\xhh
+

character encoded in hexadecimal (>= 1 hexadecimal digit) +

+
\uhhhh
+

character encoded in hexadecimal (exactly 4 hexadecimal digits) +

+
\Uhhhhhhhh
+

character encoded in hexadecimal (exactly 8 hexadecimal digits) +

+
\<space>
+

Unicode character 32 (space character) +

+
\<newline><whitespace-except-newline>*
+

This sequence expands to nothing (it is useful for splitting a long +string literal on multiple lines while respecting proper indentation +of the source code) +

+
+ +

Gambit also supports a “here string” syntax that is similar +to shell “here documents”. For example: +

+
 
> (pretty-print #<<THE-END
+hello
+world
+THE-END
+)
+"hello\nworld"
+
+ +

The here string starts with the sequence #<<. The part of the +line after the #<< up to and including the newline character is +the key. The first line afterward that matches the key marks the end +of the here string. The string contains all the characters between +the start key and the end key, with the exception of the newline +character before the end key. +

+
+ + + + + + + + + + + +
Back: 18.4 String syntaxForward: 18.6 Keyword syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.5 Symbol syntax

+ +

The lexical syntax of symbols is extended to allow a leading and +trailing vertical bar (e.g. |a\|b"c:|). The symbol’s name +corresponds verbatim to the characters between the vertical bars +except for escaped characters. The same escape sequences as for +strings are permitted except that " does not need to be escaped +and | needs to be escaped. +

+

For example: +

+
 
> (symbol->string '|a\|b"c:|)
+"a|b\"c:"
+
+ +
+ + + + + + + + + + + +
Back: 18.5 Symbol syntaxForward: 18.7 Box syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.6 Keyword syntax

+ +

The lexical syntax of keywords is like symbols, but with a colon at +the end (note that this can be changed to a leading colon by setting +the keywords-allowed? field of the readtable to the symbol +prefix). A colon by itself is not a keyword, it is a symbol. +Vertical bars can be used like symbols but the colon must be outside +the vertical bars. Note that the string returned by the +keyword->string procedure does not include the colon. +

+

For example: +

+
 
> (keyword->string 'foo:)
+"foo"
+> (map keyword? '(|ab()cd:| |ab()cd|: : ||:))
+(#f #t #f #t)
+
+ +
+ + + + + + + + + + + +
Back: 18.6 Keyword syntaxForward: 18.8 Number syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.7 Box syntax

+ +

The lexical syntax of boxes is #&obj where obj is the +content of the box. +

+

For example: +

+
 
> (list '#&"hello" '#&123)
+(#&"hello" #&123)
+> (box (box (+ 10 20)))
+#&#&30
+
+ +
+ + + + + + + + + + + +
Back: 18.7 Box syntaxForward: 18.9 Homogeneous vector syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.8 Number syntax

+ +

The lexical syntax of the special inexact real numbers is as follows: +

+
+
+inf.0
+

positive infinity +

+
-inf.0
+

negative infinity +

+
+nan.0
+

“not a number” +

+
-0.
+

negative zero (0. is the positive zero) +

+
+ +
+ + + + + + + + + + + +
Back: 18.8 Number syntaxForward: 18.10 Special #! syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.9 Homogeneous vector syntax

+ + +

Homogeneous vectors are vectors containing raw numbers of the same +type (signed or unsigned exact integers or inexact reals). There are +10 types of homogeneous vectors: +s8vector (vector of 8 bit signed integers), +u8vector (vector of 8 bit unsigned integers), +s16vector (vector of 16 bit signed integers), +u16vector (vector of 16 bit unsigned integers), +s32vector (vector of 32 bit signed integers), +u32vector (vector of 32 bit unsigned integers), +s64vector (vector of 64 bit signed integers), +u64vector (vector of 64 bit unsigned integers), +f32vector (vector of 32 bit floating point numbers), +and f64vector (vector of 64 bit floating point numbers). +

+

The external representation of homogeneous vectors is similar to +normal vectors but with the #( prefix replaced respectively +with +#s8(, #u8(, +#s16(, #u16(, +#s32(, #u32(, +#s64(, #u64(, +#f32(, and #f64(. +

+

The elements of the integer homogeneous vectors must be exact integers +fitting in the given precision. The elements of the floating point +homogeneous vectors must be inexact reals. +

+
+ + + + + + + + + + + +
Back: 18.9 Homogeneous vector syntaxForward: 18.11 Multiline comment syntax   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.10 Special #! syntax

+ +

The lexical syntax of the special #! objects is as follows: +

+
+
#!eof
+

end-of-file object +

+
#!void
+

void object +

+
#!optional
+

optional object +

+
#!rest
+

rest object +

+
#!key
+

key object +

+
+ +
+ + + + + + + + + + + +
Back: 18.10 Special #! syntaxForward: 18.12 Scheme infix syntax extension   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.11 Multiline comment syntax

+ +

Multiline comments are delimited by the tokens #| and |#. +These comments can be nested. +

+
+ + + + + + + + + + + +
Back: 18.11 Multiline comment syntaxForward: 18.12.1 SIX grammar   FastBack: 18. Lexical syntax and readtablesUp: 18. Lexical syntax and readtablesFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

18.12 Scheme infix syntax extension

+ +

The reader supports an infix syntax extension which is called SIX +(Scheme Infix eXtension). This extension is both supported by the +read procedure and in program source code. +

+

The backslash character is a delimiter that marks the beginning of a +single datum expressed in the infix syntax (the details are given +below). One way to think about it is that the backslash character +escapes the prefix syntax temporarily to use the infix syntax. For +example a three element list could be written as (X +\Y Z), the elements X and Z are expressed +using the normal prefix syntax and Y is expressed using the +infix syntax. +

+

When the reader encounters an infix datum, it constructs a syntax tree +for that particular datum. Each node of this tree is represented with +a list whose first element is a symbol indicating the type of node. +For example, (six.identifier abc) is the representation of the +infix identifier abc and (six.index (six.identifier abc) +(six.identifier i)) is the representation of the infix datum +abc[i];. +

+
+ + + + + + + + + + + +
Back: 18.12 Scheme infix syntax extensionForward: 18.12.2 SIX semantics   FastBack: 18. Lexical syntax and readtablesUp: 18.12 Scheme infix syntax extensionFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+

18.12.1 SIX grammar

+ +

The SIX grammar is given below. On the left hand side are the +production rules. On the right hand side is the datum that is +constructed by the reader. The notation $i denotes the datum +that is constructed by the reader for the ith part of the +production rule. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
<infix datum> ::=
    <stat>$1
<stat> ::=
    <if stat>$1
  | <for stat>$1
  | <while stat>$1
  | <do stat>$1
  | <switch stat>$1
  | <case stat>$1
  | <break stat>$1
  | <continue stat>$1
  | <label stat>$1
  | <goto stat>$1
  | <return stat>$1
  | <expression stat>$1
  | <procedure definition>$1
  | <variable definition> ;$1
  | <clause stat>$1
  | <compound stat>$1
  | ;(six.compound)
<if stat> ::=
    if ( <pexpr> ) <stat>(six.if $3 $5)
  | if ( <pexpr> ) <stat> else <stat>(six.if $3 $5 $7)
<for stat> ::=
    for ( <stat> ; <oexpr> ; <oexpr> ) <stat>(six.for $3 $5 $7 $9)
<while stat> ::=
    while ( <pexpr> ) <stat>(six.while $3 $5)
<do stat> ::=
    do <stat> while ( <pexpr> ) ;(six.do-while $2 $5)
<switch stat> ::=
    switch ( <pexpr> ) <stat>(six.switch $3 $5)
<case stat> ::=
    case <expr> : <stat>(six.case $2 $4)
<break stat> ::=
    break ;(six.break)
<continue stat> ::=
    continue ;(six.continue)
<label stat> ::=
    <identifier> : <stat>(six.label $1 $3)
<goto stat> ::=
    goto <expr> ;(six.goto $2)
<return stat> ::=
    return ;(six.return)
  | return <expr> ;(six.return $2)
<expression stat> ::=
    <expr> ;$1
<clause stat> ::=
    <expr> .(six.clause $1)
<pexpr> ::=
    <procedure definition>$1
  | <variable definition>$1
  | <expr>$1
<procedure definition> ::=
    <type> <id-or-prefix> ( <parameters> ) <body>(six.define-procedure $2 (six.procedure $1 $4 $6))
<variable definition> ::=
    <type> <id-or-prefix> <dimensions> <iexpr>(six.define-variable $2 $1 $3 $4)
<iexpr> ::=
    = <expr>$2
  | #f
<dimensions> ::=
  | [ <expr> ] <dimensions>($2 . $4)
  | ()
<oexpr> ::=
    <expr>$1
  | #f
<expr> ::=
    <expr18>$1
<expr18> ::=
    <expr17> :- <expr18>(six.x:-y $1 $3)
  | <expr17>$1
<expr17> ::=
    <expr17> , <expr16>(|six.x,y| $1 $3)
  | <expr16>$1
<expr16> ::=
    <expr15> := <expr16>(six.x:=y $1 $3)
  | <expr15>$1
<expr15> ::=
    <expr14> %= <expr15>(six.x%=y $1 $3)
  | <expr14> &= <expr15>(six.x&=y $1 $3)
  | <expr14> *= <expr15>(six.x*=y $1 $3)
  | <expr14> += <expr15>(six.x+=y $1 $3)
  | <expr14> -= <expr15>(six.x-=y $1 $3)
  | <expr14> /= <expr15>(six.x/=y $1 $3)
  | <expr14> <<= <expr15>(six.x<<=y $1 $3)
  | <expr14> = <expr15>(six.x=y $1 $3)
  | <expr14> >>= <expr15>(six.x>>=y $1 $3)
  | <expr14> ^= <expr15>(six.x^=y $1 $3)
  | <expr14> |= <expr15>(|six.x\|=y| $1 $3)
  | <expr14>$1
<expr14> ::=
    <expr13> : <expr14>(six.x:y $1 $3)
  | <expr13>$1
<expr13> ::=
    <expr12> ? <expr> : <expr13>(six.x?y:z $1 $3 $5)
  | <expr12>$1
<expr12> ::=
    <expr12> || <expr11>(|six.x\|\|y| $1 $3)
  | <expr11>$1
<expr11> ::=
    <expr11> && <expr10>(six.x&&y $1 $3)
  | <expr10>$1
<expr10> ::=
    <expr10> | <expr9>(|six.x\|y| $1 $3)
  | <expr9>$1
<expr9> ::=
    <expr9> ^ <expr8>(six.x^y $1 $3)
  | <expr8>$1
<expr8> ::=
    <expr8> & <expr7>(six.x&y $1 $3)
  | <expr7>$1
<expr7> ::=
    <expr7> != <expr6>(six.x!=y $1 $3)
  | <expr7> == <expr6>(six.x==y $1 $3)
  | <expr6>$1
<expr6> ::=
    <expr6> < <expr5>(six.x<y $1 $3)
  | <expr6> <= <expr5>(six.x<=y $1 $3)
  | <expr6> > <expr5>(six.x>y $1 $3)
  | <expr6> >= <expr5>(six.x>=y $1 $3)
  | <expr5>$1
<expr5> ::=
    <expr5> << <expr4>(six.x<<y $1 $3)
  | <expr5> >> <expr4>(six.x>>y $1 $3)
  | <expr4>$1
<expr4> ::=
    <expr4> + <expr3>(six.x+y $1 $3)
  | <expr4> - <expr3>(six.x-y $1 $3)
  | <expr3>$1
<expr3> ::=
    <expr3> % <expr2>(six.x%y $1 $3)
  | <expr3> * <expr2>(six.x*y $1 $3)
  | <expr3> / <expr2>(six.x/y $1 $3)
  | <expr2>$1
<expr2> ::=
    & <expr2>(six.&x $2)
  | + <expr2>(six.+x $2)
  | - <expr2>(six.-x $2)
  | * <expr2>(six.*x $2)
  | ! <expr2>(six.!x $2)
  | !(six.!)
  | ++ <expr2>(six.++x $2)
  | -- <expr2>(six.--x $2)
  | ~ <expr2>(six.~x $2)
  | new <id-or-prefix> ( <arguments> )(six.new $2 . $4)
  | <expr1>$1
<expr1> ::=
    <expr1> ++(six.x++ $1)
  | <expr1> --(six.x-- $1)
  | <expr1> ( <arguments> )(six.call $1 . $3)
  | <expr1> [ <expr> ](six.index $1 $3)
  | <expr1> -> <id-or-prefix>(six.arrow $1 $3)
  | <expr1> . <id-or-prefix>(six.dot $1 $3)
  | <expr0>$1
<expr0> ::=
    <id-or-prefix>$1
  | <string>(six.literal $1)
  | <char>(six.literal $1)
  | <number>(six.literal $1)
  | ( <expr> )$2
  | ( <block stat> )$2
  | <datum-starting-with-#-or-backquote>(six.prefix $1)
  | [ <elements> ]$2
  | <type> ( <parameters> ) <body>(six.procedure $1 $3 $5)
<block stat> ::=
    { <stat list> }(six.compound . $2)
<body> ::=
    { <stat list> }(six.procedure-body . $2)
<stat list> ::=
    <stat> <stat list>($1 . $2)
  | ()
<parameters> ::=
    <nonempty parameters>$1
  | ()
<nonempty parameters> ::=
    <parameter> , <nonempty parameters>($1 . $3)
  | <parameter>($1)
<parameter> ::=
    <type> <id-or-prefix>($2 $1)
<arguments> ::=
    <nonempty arguments>$1
  | ()
<nonempty arguments> ::=
    <expr> , <nonempty arguments>($1 . $3)
  | <expr>($1)
<elements> ::=
    <nonempty elements>$1
  | (six.null)
<nonempty elements> ::=
    <expr>(six.list $1 (six.null))
  | <expr> , <nonempty elements>(six.list $1 $3)
  | <expr> | <expr>(six.cons $1 $3)
<id-or-prefix> ::=
    <identifier>(six.identifier $1)
  | \ <datum>(six.prefix $2)
<type> ::=
    intint
  | charchar
  | boolbool
  | voidvoid
  | floatfloat
  | doubledouble
  | objobj
+ +
+ + + + + + + + + + + +
Back: 18.12.1 SIX grammarForward: 19. C-interface   FastBack: 18. Lexical syntax and readtablesUp: 18.12 Scheme infix syntax extensionFastForward: 19. C-interfaceTop: Gambit-CContents: Table of ContentsIndex: General index
+

18.12.2 SIX semantics

+ +

The semantics of SIX depends on the definition of the +six.XXX identifiers (as functions and macros). Many of +these identifiers are predefined macros which give SIX a semantics +that is close to C’s. The user may override these definitions to +change the semantics either globally or locally. For example, +six.x^y is a predefined macro that expands (six.x^y x y) +into (bitwise-xor x y). If the user prefers the ^ +operator to express exponentiation in a specific function, then in +that function six.x^y can be redefined as a macro that expands +(six.x^y x y) into (expt x y). Note that the +associativity and precedence of operators cannot be changed as that is +a syntactic issue. +

+

Note that the following identifiers are not predefined, and +consequently they do not have a predefined semantics: +six.label, six.goto, six.switch, six.case, +six.break, six.continue, six.return, +six.clause, six.x:-y, and six.!. +

+

The following is an example showing some of the predefined semantics +of SIX: +

+
 
> (list (+ 1 2) \3+4; (+ 5 6))
+(3 7 11)
+> \[ 1+2, \(+ 3 4), 5+6 ];
+(3 7 11)
+> (map (lambda (x) \(x*x-1)/log(x+1);) '(1 2 3 4))
+(0 2.730717679880512 5.7707801635558535 9.320024018394177)
+> \obj n = expt(10,5);
+> n
+100000
+> \obj t[3][10] = 88;
+> \t[0][9] = t[2][1] = 11;
+11
+> t
+#(#(88 88 88 88 88 88 88 88 88 11)
+  #(88 88 88 88 88 88 88 88 88 88)
+  #(88 11 88 88 88 88 88 88 88 88))
+> \obj radix = new parameter (10);
+> \radix(2);
+> \radix();
+2
+> \for (int i=0; i<5; i++) pp(1<<i*8);
+1
+256
+65536
+16777216
+4294967296
+> \obj \make-adder (obj x) { obj (obj y) { x+y; }; }
+> \map (new adder (100), [1,2,3,4]);
+(101 102 103 104)
+> (map (make-adder 100) (list 1 2 3 4))
+(101 102 103 104)
+
+ +
+ + + + + + + + + + + +
Back: 18.12.2 SIX semanticsForward: 19.1 The mapping of types between C and Scheme   FastBack: 18. Lexical syntax and readtablesUp: Gambit-CFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19. C-interface

+ + + +

The Gambit Scheme system offers a mechanism for interfacing Scheme code +and C code called the “C-interface”. A Scheme program indicates which +C functions it needs to have access to and which Scheme procedures can +be called from C, and the C interface automatically constructs the +corresponding Scheme procedures and C functions. The conversions needed +to transform data from the Scheme representation to the C representation +(and back), are generated automatically in accordance with the argument +and result types of the C function or Scheme procedure. +

+

The C-interface places some restrictions on the types of data that can +be exchanged between C and Scheme. The mapping of data types between C +and Scheme is discussed in the next section. The remaining sections of +this chapter describe each special form of the C-interface. +

+ + + + + + + + + + +
+ + + + + + + + + + + +
Back: 19. C-interfaceForward: 19.2 The c-declare special form   FastBack: 19. C-interfaceUp: 19. C-interfaceFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19.1 The mapping of types between C and Scheme

+ +

Scheme and C do not provide the same set of built-in data types so it is +important to understand which Scheme type is compatible with which C +type and how values get mapped from one environment to the other. To +improve compatibility a new type is added to Scheme, the foreign +object type, and the following data types are added to C: +

+
+
scheme-object
+

denotes the universal type of Scheme objects +(type ___SCMOBJ defined in gambit.h) +

+
bool
+

denotes the C++ bool type or the C int type +(type ___BOOL defined in gambit.h) +

+
int8
+

8 bit signed integer (type ___S8 defined in gambit.h) +

+
unsigned-int8
+

8 bit unsigned integer (type ___U8 defined in gambit.h) +

+
int16
+

16 bit signed integer (type ___S16 defined in gambit.h) +

+
unsigned-int16
+

16 bit unsigned integer (type ___U16 defined in gambit.h) +

+
int32
+

32 bit signed integer (type ___S32 defined in gambit.h) +

+
unsigned-int32
+

32 bit unsigned integer (type ___U32 defined in gambit.h) +

+
int64
+

64 bit signed integer (type ___S64 defined in gambit.h) +

+
unsigned-int64
+

64 bit unsigned integer (type ___U64 defined in gambit.h) +

+
float32
+

32 bit floating point number (type ___F32 defined in gambit.h) +

+
float64
+

64 bit floating point number (type ___F64 defined in gambit.h) +

+
ISO-8859-1
+

denotes ISO-8859-1 encoded characters +(8 bit unsigned integer, type ___ISO_8859_1 defined in gambit.h) +

+
UCS-2
+

denotes UCS-2 encoded characters +(16 bit unsigned integer, type ___UCS_2 defined in gambit.h) +

+
UCS-4
+

denotes UCS-4 encoded characters +(32 bit unsigned integer, type ___UCS_4 defined in gambit.h) +

+
char-string
+

denotes the C char* type when used as a null terminated string +

+
nonnull-char-string
+

denotes the nonnull C char* type when used as a null terminated string +

+
nonnull-char-string-list
+

denotes an array of nonnull C char* terminated with a null pointer +

+
ISO-8859-1-string
+

denotes ISO-8859-1 encoded strings +(null terminated string of 8 bit unsigned integers, i.e. ___ISO_8859_1*) +

+
nonnull-ISO-8859-1-string
+

denotes nonnull ISO-8859-1 encoded strings +(null terminated string of 8 bit unsigned integers, i.e. ___ISO_8859_1*) +

+
nonnull-ISO-8859-1-stringlist
+

denotes an array of nonnull ISO-8859-1 encoded strings terminated with a null pointer +

+
UTF-8-string
+

denotes UTF-8 encoded strings +(null terminated string of char, i.e. char*) +

+
nonnull-UTF-8-string
+

denotes nonnull UTF-8 encoded strings +(null terminated string of char, i.e. char*) +

+
nonnull-UTF-8-string-list
+

denotes an array of nonnull UTF-8 encoded strings terminated with a null pointer +

+
UTF-16-string
+

denotes UTF-16 encoded strings +(null terminated string of char, i.e. char*) +

+
nonnull-UTF-16-string
+

denotes nonnull UTF-16 encoded strings +(null terminated string of char, i.e. char*) +

+
nonnull-UTF-16-string-list
+

denotes an array of nonnull UTF-16 encoded strings terminated with a null pointer +

+
UCS-2-string
+

denotes UCS-2 encoded strings +(null terminated string of 16 bit unsigned integers, i.e. ___UCS_2*) +

+
nonnull-UCS-2-string
+

denotes nonnull UCS-2 encoded strings +(null terminated string of 16 bit unsigned integers, i.e. ___UCS_2*) +

+
nonnull-UCS-2-string-list
+

denotes an array of nonnull UCS-2 encoded strings terminated with a null pointer +

+
UCS-4-string
+

denotes UCS-4 encoded strings +(null terminated string of 32 bit unsigned integers, i.e. ___UCS_4*) +

+
nonnull-UCS-4-string
+

denotes nonnull UCS-4 encoded strings +(null terminated string of 32 bit unsigned integers, i.e. ___UCS_4*) +

+
nonnull-UCS-4-string-list
+

denotes an array of nonnull UCS-4 encoded strings terminated with a null pointer +

+
wchar_t-string
+

denotes wchar_t encoded strings +(null terminated string of wchar_t, i.e. wchar_t*) +

+
nonnull-wchar_t-string
+

denotes nonnull wchar_t encoded strings +(null terminated string of wchar_t, i.e. wchar_t*) +

+
nonnull-wchar_t-string-list
+

denotes an array of nonnull wchar_t encoded strings terminated with a null pointer +

+
+ +

To specify a particular C type inside the c-lambda, +c-define and c-define-type forms, the following “Scheme +notation” is used: +

+
+
Scheme notation
+

C type +

+
void
+

void +

+
bool
+

bool +

+
char
+

char (may be signed or unsigned depending on the C compiler) +

+
signed-char
+

signed char +

+
unsigned-char
+

unsigned char +

+
ISO-8859-1
+

ISO-8859-1 +

+
UCS-2
+

UCS-2 +

+
UCS-4
+

UCS-4 +

+
wchar_t
+

wchar_t +

+
short
+

short +

+
unsigned-short
+

unsigned short +

+
int
+

int +

+
unsigned-int
+

unsigned int +

+
long
+

long +

+
unsigned-long
+

unsigned long +

+
long-long
+

long long +

+
unsigned-long-long
+

unsigned long long +

+
float
+

float +

+
double
+

double +

+
int8
+

int8 +

+
unsigned-int8
+

unsigned-int8 +

+
int16
+

int16 +

+
unsigned-int16
+

unsigned-int16 +

+
int32
+

int32 +

+
unsigned-int32
+

unsigned-int32 +

+
int64
+

int64 +

+
unsigned-int64
+

unsigned-int64 +

+
float32
+

float32 +

+
float64
+

float64 +

+
(struct "c-struct-id" [tags [release-function]])
+

struct c-struct-id (where c-struct-id is the name of a +C structure; see below for the meaning of tags and release-function) +

+
(union "c-union-id" [tags [release-function]])
+

union c-union-id (where c-union-id is the name of a +C union; see below for the meaning of tags and release-function) +

+
(type "c-type-id" [tags [release-function]])
+

c-type-id (where c-type-id is an identifier naming a +C type; see below for the meaning of tags and release-function) +

+
(pointer type [tags [release-function]])
+

T* (where T is the C equivalent of type +which must be the Scheme notation of a C type; see below for the meaning +of tags and release-function) +

+
(nonnull-pointer type [tags [release-function]])
+

same as (pointer type [tags [release-function]]) +except the NULL pointer is not allowed +

+
(function (type1…) result-type)
+

function with the given argument types and result type +

+
(nonnull-function (type1…) result-type)
+

same as (function (type1…) result-type) +except the NULL pointer is not allowed +

+
char-string
+

char-string +

+
nonnull-char-string
+

nonnull-char-string +

+
nonnull-char-string-list
+

nonnull-char-string-list +

+
ISO-8859-1-string
+

ISO-8859-1-string +

+
nonnull-ISO-8859-1-string
+

nonnull-ISO-8859-1-string +

+
nonnull-ISO-8859-1-string-list
+

nonnull-ISO-8859-1-string-list +

+
UTF-8-string
+

UTF-8-string +

+
nonnull-UTF-8-string
+

nonnull-UTF-8-string +

+
nonnull-UTF-8-string-list
+

nonnull-UTF-8-string-list +

+
UTF-16-string
+

UTF-16-string +

+
nonnull-UTF-16-string
+

nonnull-UTF-16-string +

+
nonnull-UTF-16-string-list
+

nonnull-UTF-16-string-list +

+
UCS-2-string
+

UCS-2-string +

+
nonnull-UCS-2-string
+

nonnull-UCS-2-string +

+
nonnull-UCS-2-string-list
+

nonnull-UCS-2-string-list +

+
UCS-4-string
+

UCS-4-string +

+
nonnull-UCS-4-string
+

nonnull-UCS-4-string +

+
nonnull-UCS-4-string-list
+

nonnull-UCS-4-string-list +

+
wchar_t-string
+

wchar_t-string +

+
nonnull-wchar_t-string
+

nonnull-wchar_t-string +

+
nonnull-wchar_t-string-list
+

nonnull-wchar_t-string-list +

+
scheme-object
+

scheme-object +

+
name
+

appropriate translation of name (where name +is a C type defined with c-define-type) +

+
"c-type-id"
+

c-type-id (this form is equivalent to (type "c-type-id")) +

+
+ +

The struct, union, type, pointer and +nonnull-pointer types are “foreign types” and they are +represented on the Scheme side as “foreign objects”. A foreign object +is internally represented as a pointer. This internal pointer is +identical to the C pointer being represented in the case of the +pointer and nonnull-pointer types. +

+

In the case of the struct, union and type types, +the internal pointer points to a copy of the C data type being +represented. When an instance of one of these types is converted from C +to Scheme, a block of memory is allocated from the C heap and +initialized with the instance and then a foreign object is allocated +from the Scheme heap and initialized with the pointer to this copy. +This approach may appear overly complex, but it allows the conversion of +C++ classes that do not have a zero parameter constructor or an +assignment method (i.e. when compiling with a C++ compiler an instance +is copied using new type (instance), which calls the +copy-constructor of type if it is a class; type’s assignment +operator is never used). Conversion from Scheme to C simply +dereferences the internal pointer (no allocation from the C heap is +performed). Deallocation of the copy on the C heap is under the control +of the release function attached to the foreign object (see below). +

+

The optional tags field of foreign type specifications is used +for type checking on the Scheme side. The tags field must be +#f, a symbol or a non-empty list of symbols. When it is not +specified the tags field defaults to a symbol whose name, as +returned by symbol->string, is the C type declaration for that +type. For example the symbol char** is the default for the +type (pointer (pointer char)). A tags field that is a +single symbol is equivalent to a list containing only that symbol. +The first symbol in the list of tags is the primary tag. For example +the primary tag of the type (pointer char) is char* and +the primary tag of the type (pointer char (foo bar)) is +foo. +

+

Type compatibility between two foreign types depends on their tags. +An instance of a foreign type T can be used where a foreign type +E is expected if and only if +

+ + +

For the safest code a tags field of #f should be used +sparingly, as it completely bypasses type checking. The external +representation of Scheme foreign objects (used by the write +procedure) contains the primary tag (if the tags field is not +#f), and the hexadecimal address denoted by the internal +pointer, for example #<char** #2 0x2AAC535C>. Note that the +hexadecimal address is in C notation, which can be easily transferred +to a C debugger with a “cut-and-paste”. +

+

A release-function can also be specified within a foreign type +specification. The release-function must be #f or a string +naming a C function with a single parameter of type void* (in +which the internal pointer is passed) and with a result of type +___SCMOBJ (for returning an error code). When the +release-function is not specified or is #f a default +function is constructed by the C-interface. This default function does +nothing in the case of the pointer and nonnull-pointer +types (deallocation is not the responsibility of the C-interface) and +returns the fixnum ___FIX(___NO_ERR) to indicate no error. In +the case of the struct, union and type types, the +default function reclaims the copy on the C heap referenced by the +internal pointer (when using a C++ compiler this is done using +delete (type*)internal-pointer, which calls the +destructor of type if it is a class) and returns +___FIX(___NO_ERR). In many situations the default +release-function will perform the appropriate cleanup for the +foreign type. However, in certain cases special operations (such as +decrementing a reference count, removing the object from a table, etc) +must be performed. For such cases a user supplied +release-function is needed. +

+

The release-function is invoked at most once for any foreign +object. After the release-function is invoked, the foreign +object is considered “released” and can no longer be used in a +foreign type conversion. When the garbage collector detects that a +foreign object is no longer reachable by the program, it will invoke +the release-function if the foreign object is not yet released. +When there is a need to release the foreign object promptly, the +program can explicitly call (foreign-release! obj) which +invokes the release-function if the foreign object is not yet +released, and does nothing otherwise. The call +(foreign-released? obj) returns a boolean indicating +whether the foreign object obj has been released yet or not. +The call (foreign-address obj) returns the address +denoted by the internal pointer of foreign object obj or 0 if it +has been released. The call (foreign? obj) tests that +obj is a foreign object. Finally the call (foreign-tags +obj) returns the list of tags of foreign object obj, or +#f. +

+

The following table gives the C types to which each Scheme type +can be converted: +

+
+
Scheme type
+

Allowed target C types +

+
boolean #f
+

scheme-object; bool; +pointer; +function; +char-string; +ISO-8859-1-string; +UTF-8-string; +UTF-16-string; +UCS-2-string; +UCS-4-string; +wchar_t-string +

+
boolean #t
+

scheme-object; bool +

+
character
+

scheme-object; bool; +[[un]signed] char; ISO-8859-1; UCS-2; +UCS-4; wchar_t +

+
exact integer
+

scheme-object; bool; [unsigned-] +int8/int16/int32/int64; [unsigned] +short/int/long +

+
inexact real
+

scheme-object; bool; float; double; float32; float64 +

+
string
+

scheme-object; bool; +char-string; +nonnull-char-string; +ISO-8859-1-string; +nonnull-ISO-8859-1-string; +UTF-8-string; +nonnull-UTF-8-string; +UTF-16-string; +nonnull-UTF-16-string; +UCS-2-string; +nonnull-UCS-2-string; +UCS-4-string; +nonnull-UCS-4-string; +wchar_t-string; +nonnull-wchar_t-string +

+
foreign object
+

scheme-object; bool; struct/union/type/pointer/nonnull-pointer with the appropriate tags +

+
vector
+

scheme-object; bool +

+
symbol
+

scheme-object; bool +

+
procedure
+

scheme-object; bool; +function; +nonnull-function +

+
other objects
+

scheme-object; bool +

+
+ +

The following table gives the Scheme types to which each C type +will be converted: +

+
+
C type
+

Resulting Scheme type +

+
scheme-object
+

the Scheme object encoded +

+
bool
+

boolean +

+
[[un]signed] char; ISO-8859-1; UCS-2; UCS-4; wchar_t
+

character +

+
[unsigned-] int8/int16/int32/int64; [unsigned] short/int/long
+

exact integer +

+
float; double; float32; float64
+

inexact real +

+
char-string; ISO-8859-1-string; UTF-8-string; UTF-16-string; UCS-2-string; UCS-4-string; wchar_t-string
+

string or #f if it is equal to NULL +

+
nonnull-char-string; nonnull-ISO-8859-1-string; nonnull-UTF-8-string; nonnull-UTF-16-string; nonnull-UCS-2-string; nonnull-UCS-4-string; nonnull-wchar_t-string
+

string +

+
struct/union/type/pointer/nonnull-pointer
+

foreign object with the appropriate tags +or #f in the case of a pointer equal to NULL +

+
function
+

procedure or #f if it is equal to NULL +

+
nonnull-function
+

procedure +

+
void
+

void object +

+
+ +

All Scheme types are compatible with the C types scheme-object +and bool. Conversion to and from the C type +scheme-object is the identity function on the object encoding. +This provides a low-level mechanism for accessing Scheme’s object +representation from C (with the help of the macros in the +gambit.h header file). When a C bool type is expected, +an extended Scheme boolean can be passed (#f is converted to 0 +and all other values are converted to 1). +

+

The Scheme boolean #f can be passed to the C environment where +a char-string, ISO-8859-1-string, UTF-8-string, +UTF-16-string, UCS-2-string, UCS-4-string, +wchar_t-string, pointer or function type is +expected. In this case, #f is converted to the NULL +pointer. C bools are extended booleans so any value different +from 0 represents true. Thus, a C bool passed to the Scheme +environment is mapped as follows: 0 to #f and all other values +to #t. +

+

A Scheme character passed to the C environment where any C character +type is expected is converted to the corresponding character in the C +environment. An error is signaled if the Scheme character does not fit +in the C character. Any C character type passed to Scheme is converted +to the corresponding Scheme character. An error is signaled if the C +character does not fit in the Scheme character. +

+

A Scheme exact integer passed to the C environment where a C integer +type (other than char) is expected is converted to the +corresponding integral value. An error is signaled if the value falls +outside of the range representable by that integral type. C integer +values passed to the Scheme environment are mapped to the same Scheme +exact integer. If the value is outside the fixnum range, a bignum is +created. +

+

A Scheme inexact real passed to the C environment is converted to the +corresponding float, double, float32 or +float64 value. C float, double, float32 and +float64 values passed to the Scheme environment are mapped to the +closest Scheme inexact real. +

+

Scheme’s rational numbers and complex numbers are not compatible with +any C numeric type. +

+

A Scheme string passed to the C environment where any C string type is +expected is converted to a null terminated string using the appropriate +encoding. The C string is a fresh copy of the Scheme string. If the C +string was created for an argument of a c-lambda, the C string +will be reclaimed when the c-lambda returns. If the C string was +created for returning the result of a c-define to C, the caller +is responsible for reclaiming the C string with a call to the +___release_string function (see below for an example). Any C +string type passed to the Scheme environment causes the creation of a +fresh Scheme string containing a copy of the C string (unless the C +string is equal to NULL, in which case it is converted to +#f). +

+

A foreign type passed to the Scheme environment causes the creation +and initialization of a Scheme foreign object with the appropriate +tags (except for the case of a pointer equal to NULL +which is converted to #f). A Scheme foreign object can be +passed where a foreign type is expected, on the condition that the +tags are compatible and the Scheme foreign object is not yet released. +The value #f is also acceptable for a pointer type, and +is converted to NULL. +

+

Scheme procedures defined with the c-define special form can be +passed where the function and nonnull-function types are +expected. The value #f is also acceptable for a function +type, and is converted to NULL. No other Scheme procedures are +acceptable. Conversion from the function and +nonnull-function types to Scheme procedures is not currently +implemented. +

+
+ + + + + + + + + + + +
Back: 19.1 The mapping of types between C and SchemeForward: 19.3 The c-initialize special form   FastBack: 19. C-interfaceUp: 19. C-interfaceFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19.2 The c-declare special form

+ + +
(c-declare c-declaration)special form
+ +

Initially, the C file produced by gsc contains only an +#include of gambit.h. This header file provides a +number of macro and procedure declarations to access the Scheme object +representation. The special form c-declare adds +c-declaration (which must be a string containing the C +declarations) to the C file. This string is copied to the C file on a +new line so it can start with preprocessor directives. All types of C +declarations are allowed (including type declarations, variable +declarations, function declarations, #include directives, +#defines, and so on). These declarations are visible to +subsequent c-declares, c-initializes, and +c-lambdas, and c-defines in the same module. The most +common use of this special form is to declare the external functions +that are referenced in c-lambda special forms. Such functions +must either be declared explicitly or by including a header file which +contains the appropriate C declarations. +

+

The c-declare special form does not return a value. +It can only appear at top level. +

+

For example: +

+
 
(c-declare #<<c-declare-end
+
+#include <stdio.h>
+
+extern char *getlogin ();
+
+#ifdef sparc
+char *host = "sparc";
+#else
+char *host = "unknown";
+#endif
+
+FILE *tfile;
+
+c-declare-end
+)
+
+ + + +
+ + + + + + + + + + + +
Back: 19.2 The c-declare special formForward: 19.4 The c-lambda special form   FastBack: 19. C-interfaceUp: 19. C-interfaceFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19.3 The c-initialize special form

+ + +
(c-initialize c-code)special form
+ +

Just after the program is loaded and before control is passed to the +Scheme code, each C file is initialized by calling its associated +initialization function. The body of this function is normally empty +but it can be extended by using the c-initialize form. Each +occurence of the c-initialize form adds code to the body of the +initialization function in the order of appearance in the source file. +c-code must be a string containing the C code to execute. This +string is copied to the C file on a new line so it can start with +preprocessor directives. +

+

The c-initialize special form does not return a value. +It can only appear at top level. +

+

For example: +

+
 
(c-initialize "tfile = tmpfile ();")
+
+ + + +
+ + + + + + + + + + + +
Back: 19.3 The c-initialize special formForward: 19.5 The c-define special form   FastBack: 19. C-interfaceUp: 19. C-interfaceFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19.4 The c-lambda special form

+ + +
(c-lambda (type1…) result-type c-name-or-code)special form
+ +

The c-lambda special form makes it possible to create a Scheme +procedure that will act as a representative of some C function or C code +sequence. The first subform is a list containing the type of each +argument. The type of the function’s result is given next. Finally, +the last subform is a string that either contains the name of the C +function to call or some sequence of C code to execute. Variadic C +functions are not supported. The resulting Scheme procedure takes +exactly the number of arguments specified and delivers them in the same +order to the C function. When the Scheme procedure is called, the +arguments will be converted to their C representation and then the C +function will be called. The result returned by the C function will be +converted to its Scheme representation and this value will be returned +from the Scheme procedure call. An error will be signaled if some +conversion is not possible. The temporary memory allocated from the C +heap for the conversion of the arguments and result will be reclaimed +whether there is an error or not. +

+

When c-name-or-code is not a valid C identifier, it is treated +as an arbitrary piece of C code. Within the C code the variables +___arg1, ___arg2, etc. can be referenced to access the +converted arguments. Similarly, the result to be returned from the +call should be assigned to the variable ___result except when +the result is of type struct, union, type, +pointer, nonnull-pointer, function or +nonnull-function in which case a pointer must be assigned to +the variable ___result_voidstar which is of type void*. +For results of type pointer, nonnull-pointer, +function and nonnull-function, the value assigned to the +variable ___result_voidstar must be the pointer or function +cast to void*. For results of type struct, +union, and type, the value assigned to the variable +___result_voidstar must be a pointer to a memory allocated +block containing a copy of the result. Note that this block will be +reclaimed by the release-function associated with the type. +If no result needs to be returned, the result-type should be +void and no assignment to the variable ___result or +___result_voidstar should take place. Note that the C code +should not contain return statements as this is meaningless. +Control must always fall off the end of the C code. The C code is +copied to the C file on a new line so it can start with preprocessor +directives. Moreover the C code is always placed at the head of a +compound statement whose lifetime encloses the C to Scheme conversion of +the result. Consequently, temporary storage (strings in particular) +declared at the head of the C code can be returned by assigning them to +___result or ___result_voidstar. In the +c-name-or-code, the macro ___AT_END may be defined as the +piece of C code to execute before control is returned to Scheme but +after the result is converted to its Scheme representation. This is +mainly useful to deallocate temporary storage contained in the result. +

+

When passed to the Scheme environment, the C void type is +converted to the void object. +

+

For example: +

+
 
(define fopen
+  (c-lambda (nonnull-char-string nonnull-char-string)
+            (pointer "FILE")
+   "fopen"))
+
+(define fgetc
+  (c-lambda ((pointer "FILE"))
+            int
+   "fgetc"))
+
+(let ((f (fopen "datafile" "r")))
+  (if f (write (fgetc f))))
+
+(define char-code
+  (c-lambda (char) int "___result = ___arg1;"))
+
+(define host
+  ((c-lambda () nonnull-char-string "___result = host;")))
+
+(define stdin
+  ((c-lambda () (pointer "FILE") "___result_voidstar = stdin;")))
+
+((c-lambda () void
+#<<c-lambda-end
+  printf( "hello\n" );
+  printf( "world\n" );
+c-lambda-end
+))
+
+(define pack-1-char
+  (c-lambda (char)
+            nonnull-char-string
+#<<c-lambda-end
+   ___result = malloc (2);
+   if (___result != NULL) { ___result[0] = ___arg1; ___result[1] = 0; }
+   #define ___AT_END if (___result != NULL) free (___result);
+c-lambda-end
+))
+
+(define pack-2-chars
+  (c-lambda (char char)
+            nonnull-char-string
+#<<c-lambda-end
+   char s[3];
+   s[0] = ___arg1;
+   s[1] = ___arg2;
+   s[2] = 0;
+   ___result = s;
+c-lambda-end
+))
+
+ + + +
+ + + + + + + + + + + +
Back: 19.4 The c-lambda special formForward: 19.6 The c-define-type special form   FastBack: 19. C-interfaceUp: 19. C-interfaceFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19.5 The c-define special form

+ + +
(c-define (variable define-formals) (type1…) result-type c-name scope body)special form
+ +

The c-define special form makes it possible to create a C +function that will act as a representative of some Scheme procedure. A +C function named c-name as well as a Scheme procedure bound to the +variable variable are defined. The parameters of the Scheme +procedure are define-formals and its body is at the end of the +form. The type of each argument of the C function, its result type and +c-name (which must be a string) are specified after the parameter +specification of the Scheme procedure. When the C function c-name +is called from C, its arguments are converted to their Scheme +representation and passed to the Scheme procedure. The result of the +Scheme procedure is then converted to its C representation and the C +function c-name returns it to its caller. +

+

The scope of the C function can be changed with the scope +parameter, which must be a string. This string is placed immediately +before the declaration of the C function. So if scope is the +string "static", the scope of c-name is local to the module +it is in, whereas if scope is the empty string, c-name is +visible from other modules. +

+

The c-define special form does not return a value. +It can only appear at top level. +

+

For example: +

+
 
(c-define (proc x #!optional (y x) #!rest z) (int int char float) int "f" ""
+  (write (cons x (cons y z)))
+  (newline)
+  (+ x y))
+
+(proc 1 2 #\x 1.5) => 3 and prints (1 2 #\x 1.5)
+(proc 1)           => 2 and prints (1 1)
+
+; if f is called from C with the call  f (1, 2, 'x', 1.5)
+; the value 3 is returned and (1 2 #\x 1.5) is printed.
+; f has to be called with 4 arguments.
+
+ + + +

The c-define special form is particularly useful when the +driving part of an application is written in C and Scheme procedures +are called directly from C. The Scheme part of the application is in +a sense a “server” that is providing services to the C part. The +Scheme procedures that are to be called from C need to be defined +using the c-define special form. Before it can be used, the +Scheme part must be initialized with a call to the function +___setup. Before the program terminates, it must call the +function ___cleanup so that the Scheme part may do final +cleanup. A sample application is given in the file +tests/server.scm. +

+ + +
+ + + + + + + + + + + +
Back: 19.5 The c-define special formForward: 19.7 Continuations and the C-interface   FastBack: 19. C-interfaceUp: 19. C-interfaceFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19.6 The c-define-type special form

+ + +
(c-define-type name type [c-to-scheme scheme-to-c [cleanup]])special form
+ +

This form associates the type identifier name to the C type +type. The name must not clash with predefined types +(e.g. char-string, ISO-8859-1, etc.) or with types previously +defined with c-define-type in the same file. The +c-define-type special form does not return a value. It can only +appear at top level. +

+

If only the two parameters name and type are supplied then +after this definition, the use of name in a type specification is +synonymous to type. +

+

For example: +

+
 
(c-define-type FILE "FILE")
+(c-define-type FILE* (pointer FILE))
+(c-define-type time-struct-ptr (pointer (struct "tms")))
+(define fopen (c-lambda (char-string char-string) FILE* "fopen"))
+(define fgetc (c-lambda (FILE*) int "fgetc"))
+
+ +

Note that identifiers are not case-sensitive in standard Scheme but it +is good programming practice to use a name with the same case as +in C. +

+

If four or more parameters are supplied, then type must be a +string naming the C type, c-to-scheme and scheme-to-c must +be strings suffixing the C macros that convert data of that type between +C and Scheme. If cleanup is supplied it must be a boolean +indicating whether it is necessary to perform a cleanup operation (such +as freeing memory) when data of that type is converted from Scheme to C +(it defaults to #t). The cleanup information is used when the C +stack is unwound due to a continuation invocation (see +Continuations and the C-interface). Although it is safe to always specify #t, +it is more efficient in time and space to specify #f because the +unwinding mechanism can skip C-interface frames which only contain +conversions of data types requiring no cleanup. Two pairs of C macros +need to be defined for conversions performed by c-lambda forms +and two pairs for conversions performed by c-define forms: +

+
 
___BEGIN_CFUN_scheme-to-c(___SCMOBJ, type, int)
+___END_CFUN_scheme-to-c(___SCMOBJ, type, int)
+
+___BEGIN_CFUN_c-to-scheme(type, ___SCMOBJ)
+___END_CFUN_c-to-scheme(type, ___SCMOBJ)
+
+___BEGIN_SFUN_c-to-scheme(type, ___SCMOBJ, int)
+___END_SFUN_c-to-scheme(type, ___SCMOBJ, int)
+
+___BEGIN_SFUN_scheme-to-c(___SCMOBJ, type)
+___END_SFUN_scheme-to-c(___SCMOBJ, type)
+
+ +

The macros prefixed with ___BEGIN perform the conversion and +those prefixed with ___END perform any cleanup necessary (such as +freeing memory temporarily allocated for the conversion). The macro +___END_CFUN_scheme-to-c must free the result of the +conversion if it is memory allocated, and +___END_SFUN_scheme-to-c must not (i.e. it is the +responsibility of the caller to free the result). +

+

The first parameter of these macros is the C variable that contains the +value to be converted, and the second parameter is the C variable in +which to store the converted value. The third parameter, when present, +is the index (starting at 1) of the parameter of the c-lambda or +c-define form that is being converted (this is useful for +reporting precise error information when a conversion is impossible). +

+

To allow for type checking, the first three ___BEGIN macros must +expand to an unterminated compound statement prefixed by an if, +conditional on the absence of type check error: +

+
 
if ((___err = conversion_operation) == ___FIX(___NO_ERR)) {
+
+ +

The last ___BEGIN macro must expand to an unterminated compound +statement: +

+
 
{ ___err = conversion_operation;
+
+ +

If type check errors are impossible then a ___BEGIN macro can +simply expand to an unterminated compound statement performing the +conversion: +

+
 
{ conversion_operation;
+
+ +

The ___END macros must expand to a statement, or to nothing if no +cleanup is required, followed by a closing brace (to terminate the +compound statement started at the corresponding ___BEGIN macro). +

+

The conversion_operation is typically a function call that returns +an error code value of type ___SCMOBJ (the error codes are defined in +gambit.h, and the error code ___FIX(___UNKNOWN_ERR) is available +for generic errors). conversion_operation can also set the +variable ___errmsg of type ___SCMOBJ to a specific Scheme +string error message. +

+

Below is a simple example showing how to interface to an EBCDIC +character type. Memory allocation is not needed for conversion and type +check errors are impossible when converting EBCDIC to Scheme characters, +but they are possible when converting from Scheme characters to EBCDIC +since Gambit supports Unicode characters. +

+
 
(c-declare #<<c-declare-end
+
+typedef char EBCDIC; /* EBCDIC encoded characters */
+
+void put_char (EBCDIC c) { ... } /* EBCDIC I/O functions */
+EBCDIC get_char (void) { ... }
+
+char EBCDIC_to_ISO_8859_1[256] = { ... }; /* conversion tables */
+char ISO_8859_1_to_EBCDIC[256] = { ... };
+
+___SCMOBJ SCMOBJ_to_EBCDIC (___SCMOBJ src, EBCDIC *dst)
+{
+  int x = ___INT(src); /* convert from Scheme character to int */
+  if (x > 255) return ___FIX(___UNKNOWN_ERR);
+  *dst = ISO_8859_1_to_EBCDIC[x];
+  return ___FIX(___NO_ERR);
+}
+
+#define ___BEGIN_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) \
+if ((___err = SCMOBJ_to_EBCDIC (src, &dst)) == ___FIX(___NO_ERR)) {
+#define ___END_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) }
+
+#define ___BEGIN_CFUN_EBCDIC_to_SCMOBJ(src,dst) \
+{ dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
+#define ___END_CFUN_EBCDIC_to_SCMOBJ(src,dst) }
+
+#define ___BEGIN_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) \
+{ dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
+#define ___END_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) }
+
+#define ___BEGIN_SFUN_SCMOBJ_to_EBCDIC(src,dst) \
+{ ___err = SCMOBJ_to_EBCDIC (src, &dst);
+#define ___END_SFUN_SCMOBJ_to_EBCDIC(src,dst) }
+
+c-declare-end
+)
+
+(c-define-type EBCDIC "EBCDIC" "EBCDIC_to_SCMOBJ" "SCMOBJ_to_EBCDIC" #f)
+
+(define put-char (c-lambda (EBCDIC) void "put_char"))
+(define get-char (c-lambda () EBCDIC "get_char"))
+
+(c-define (write-EBCDIC c) (EBCDIC) void "write_EBCDIC" ""
+  (write-char c))
+
+(c-define (read-EBCDIC) () EBCDIC "read_EBCDIC" ""
+  (read-char))
+
+ +

Below is a more complex example that requires memory allocation when +converting from C to Scheme. It is an interface to a 2D point +type which is represented in Scheme by a pair of integers. The +conversion of the x and y components is done by calls to +the conversion macros for the int type (defined in +gambit.h). Note that no cleanup is necessary when converting +from Scheme to C (i.e. the last parameter of the c-define-type is +#f). +

+
 
(c-declare #<<c-declare-end
+
+typedef struct { int x, y; } point;
+
+void line_to (point p) { ... }
+point get_mouse (void) { ... }
+point add_points (point p1, point p2) { ... }
+
+___SCMOBJ SCMOBJ_to_POINT (___SCMOBJ src, point *dst, int arg_num)
+{
+  ___SCMOBJ ___err = ___FIX(___NO_ERR);
+  if (!___PAIRP(src))
+    ___err = ___FIX(___UNKNOWN_ERR);
+  else
+    {
+      ___SCMOBJ car = ___CAR(src);
+      ___SCMOBJ cdr = ___CDR(src);
+      ___BEGIN_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
+      ___BEGIN_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
+      ___END_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
+      ___END_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
+    }
+  return ___err;
+}
+
+___SCMOBJ POINT_to_SCMOBJ (point src, ___SCMOBJ *dst, int arg_num)
+{
+  ___SCMOBJ ___err = ___FIX(___NO_ERR);
+  ___SCMOBJ x_scmobj;
+  ___SCMOBJ y_scmobj;
+  ___BEGIN_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
+  ___BEGIN_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
+  *dst = ___EXT(___make_pair) (x_scmobj, y_scmobj, ___STILL);
+  if (___FIXNUMP(*dst))
+    ___err = *dst; /* return allocation error */
+  ___END_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
+  ___END_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
+  return ___err;
+}
+
+#define ___BEGIN_CFUN_SCMOBJ_to_POINT(src,dst,i) \
+if ((___err = SCMOBJ_to_POINT (src, &dst, i)) == ___FIX(___NO_ERR)) {
+#define ___END_CFUN_SCMOBJ_to_POINT(src,dst,i) }
+
+#define ___BEGIN_CFUN_POINT_to_SCMOBJ(src,dst) \
+if ((___err = POINT_to_SCMOBJ (src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
+#define ___END_CFUN_POINT_to_SCMOBJ(src,dst) \
+___EXT(___release_scmobj) (dst); }
+
+#define ___BEGIN_SFUN_POINT_to_SCMOBJ(src,dst,i) \
+if ((___err = POINT_to_SCMOBJ (src, &dst, i)) == ___FIX(___NO_ERR)) {
+#define ___END_SFUN_POINT_to_SCMOBJ(src,dst,i) \
+___EXT(___release_scmobj) (dst); }
+
+#define ___BEGIN_SFUN_SCMOBJ_to_POINT(src,dst) \
+{ ___err = SCMOBJ_to_POINT (src, &dst, ___RETURN_POS);
+#define ___END_SFUN_SCMOBJ_to_POINT(src,dst) }
+
+c-declare-end
+)
+
+(c-define-type point "point" "POINT_to_SCMOBJ" "SCMOBJ_to_POINT" #f)
+
+(define line-to (c-lambda (point) void "line_to"))
+(define get-mouse (c-lambda () point "get_mouse"))
+(define add-points (c-lambda (point point) point "add_points"))
+
+(c-define (write-point p) (point) void "write_point" ""
+  (write p))
+
+(c-define (read-point) () point "read_point" ""
+  (read))
+
+ +

An example that requires memory allocation when converting from C to +Scheme and Scheme to C is shown below. It is an interface to a +“null-terminated array of strings” type which is represented in Scheme +by a list of strings. Note that some cleanup is necessary when +converting from Scheme to C. +

+
 
(c-declare #<<c-declare-end
+
+#include <stdlib.h>
+#include <unistd.h>
+
+extern char **environ;
+
+char **get_environ (void) { return environ; }
+
+void free_strings (char **strings)
+{
+  char **ptr = strings;
+  while (*ptr != NULL)
+    {
+      ___EXT(___release_string) (*ptr);
+      ptr++;
+    }
+  free (strings);
+}
+
+___SCMOBJ SCMOBJ_to_STRINGS (___SCMOBJ src, char ***dst, int arg_num)
+{
+  /*
+   * Src is a list of Scheme strings.  Dst will be a null terminated
+   * array of C strings.
+   */
+
+  int i;
+  ___SCMOBJ lst = src;
+  int len = 4; /* start with a small result array */
+  char **result = (char**) malloc (len * sizeof (char*));
+
+  if (result == NULL)
+    return ___FIX(___HEAP_OVERFLOW_ERR);
+
+  i = 0;
+  result[i] = NULL; /* always keep array null terminated */
+
+  while (___PAIRP(lst))
+    {
+      ___SCMOBJ scm_str = ___CAR(lst);
+      char *c_str;
+      ___SCMOBJ ___err;
+
+      if (i >= len-1) /* need to grow the result array? */
+        {
+          char **new_result;
+          int j;
+
+          len = len * 3 / 2;
+          new_result = (char**) malloc (len * sizeof (char*));
+          if (new_result == NULL)
+            {
+              free_strings (result);
+              return ___FIX(___HEAP_OVERFLOW_ERR);
+            }
+          for (j=i; j>=0; j--)
+            new_result[j] = result[j];
+          free (result);
+          result = new_result;
+        }
+
+      ___err = ___EXT(___SCMOBJ_to_CHARSTRING) (scm_str, &c_str, arg_num);
+
+      if (___err != ___FIX(___NO_ERR))
+        {
+          free_strings (result);
+          return ___err;
+        }
+
+      result[i++] = c_str;
+      result[i] = NULL;
+      lst = ___CDR(lst);
+    }
+
+  if (!___NULLP(lst))
+    {
+      free_strings (result);
+      return ___FIX(___UNKNOWN_ERR);
+    }
+
+  /*
+   * Note that the caller is responsible for calling free_strings
+   * when it is done with the result.
+   */
+
+  *dst = result;
+  return ___FIX(___NO_ERR);
+}
+
+___SCMOBJ STRINGS_to_SCMOBJ (char **src, ___SCMOBJ *dst, int arg_num)
+{
+  ___SCMOBJ ___err = ___FIX(___NO_ERR);
+  ___SCMOBJ result = ___NUL; /* start with the empty list */
+  int i = 0;
+
+  while (src[i] != NULL)
+    i++;
+
+  /* build the list of strings starting at the tail */
+
+  while (--i >= 0)
+    {
+      ___SCMOBJ scm_str;
+      ___SCMOBJ new_result;
+
+      /*
+       * Invariant: result is either the empty list or a ___STILL pair
+       * with reference count equal to 1.  This is important because
+       * it is possible that ___CHARSTRING_to_SCMOBJ and ___make_pair
+       * will invoke the garbage collector and we don't want the
+       * reference in result to become invalid (which would be the
+       * case if result was a ___MOVABLE pair or if it had a zero
+       * reference count).
+       */
+
+      ___err = ___EXT(___CHARSTRING_to_SCMOBJ) (src[i], &scm_str, arg_num);
+
+      if (___err != ___FIX(___NO_ERR))
+        {
+          ___EXT(___release_scmobj) (result); /* allow GC to reclaim result */
+          return ___FIX(___UNKNOWN_ERR);
+        }
+
+      /*
+       * Note that scm_str will be a ___STILL object with reference
+       * count equal to 1, so there is no risk that it will be
+       * reclaimed or moved if ___make_pair invokes the garbage
+       * collector.
+       */
+
+      new_result = ___EXT(___make_pair) (scm_str, result, ___STILL);
+
+      /*
+       * We can zero the reference count of scm_str and result (if
+       * not the empty list) because the pair now references these
+       * objects and the pair is reachable (it can't be reclaimed
+       * or moved by the garbage collector).
+       */
+
+      ___EXT(___release_scmobj) (scm_str);
+      ___EXT(___release_scmobj) (result);
+
+      result = new_result;
+
+      if (___FIXNUMP(result))
+        return result; /* allocation failed */
+    }
+
+  /*
+   * Note that result is either the empty list or a ___STILL pair
+   * with a reference count equal to 1.  There will be a call to
+   * ___release_scmobj later on (in ___END_CFUN_STRINGS_to_SCMOBJ
+   * or ___END_SFUN_STRINGS_to_SCMOBJ) that will allow the garbage
+   * collector to reclaim the whole list of strings when the Scheme
+   * world no longer references it.
+   */
+
+  *dst = result;
+  return ___FIX(___NO_ERR);
+}
+
+#define ___BEGIN_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
+if ((___err = SCMOBJ_to_STRINGS (src, &dst, i)) == ___FIX(___NO_ERR)) {
+#define ___END_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
+free_strings (dst); }
+
+#define ___BEGIN_CFUN_STRINGS_to_SCMOBJ(src,dst) \
+if ((___err = STRINGS_to_SCMOBJ (src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
+#define ___END_CFUN_STRINGS_to_SCMOBJ(src,dst) \
+___EXT(___release_scmobj) (dst); }
+
+#define ___BEGIN_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
+if ((___err = STRINGS_to_SCMOBJ (src, &dst, i)) == ___FIX(___NO_ERR)) {
+#define ___END_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
+___EXT(___release_scmobj) (dst); }
+
+#define ___BEGIN_SFUN_SCMOBJ_to_STRINGS(src,dst) \
+{ ___err = SCMOBJ_to_STRINGS (src, &dst, ___RETURN_POS);
+#define ___END_SFUN_SCMOBJ_to_STRINGS(src,dst) }
+
+c-declare-end
+)
+
+(c-define-type char** "char**" "STRINGS_to_SCMOBJ" "SCMOBJ_to_STRINGS")
+
+(define execv (c-lambda (char-string char**) int "execv"))
+(define get-environ (c-lambda () char** "get_environ"))
+
+(c-define (write-strings x) (char**) void "write_strings" ""
+  (write x))
+
+(c-define (read-strings) () char** "read_strings" ""
+  (read))
+
+ + + +
+ + + + + + + + + + + +
Back: 19.6 The c-define-type special formForward: 20. System limitations   FastBack: 19. C-interfaceUp: 19. C-interfaceFastForward: 20. System limitationsTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

19.7 Continuations and the C-interface

+ + +

The C-interface allows C to Scheme calls to be nested. This means +that during a call from C to Scheme another call from C to Scheme +can be performed. This case occurs in the following program: +

+
 
(c-declare #<<c-declare-end
+
+int p (char *); /* forward declarations */
+int q (void);
+
+int a (char *x) { return 2 * p (x+1); }
+int b (short y) { return y + q (); }
+
+c-declare-end
+)
+
+(define a (c-lambda (char-string) int "a"))
+(define b (c-lambda (short) int "b"))
+
+(c-define (p z) (char-string) int "p" ""
+  (+ (b 10) (string-length z)))
+
+(c-define (q) () int "q" ""
+  123)
+
+(write (a "hello"))
+
+ +

In this example, the main Scheme program calls the C function a +which calls the Scheme procedure p which in turn calls the C +function b which finally calls the Scheme procedure q. +

+

Gambit-C maintains the Scheme continuation separately from the C stack, +thus allowing the Scheme continuation to be unwound independently from +the C stack. The C stack frame created for the C function f is +only removed from the C stack when control returns from f or when +control returns to a C function “above” f. Special care is +required for programs which escape to Scheme (using first-class +continuations) from a Scheme to C (to Scheme) call because the C stack +frame will remain on the stack. The C stack may overflow if this +happens in a loop with no intervening return to a C function. To avoid +this problem make sure the C stack gets cleaned up by executing a normal +return from a Scheme to C call. +

+
+ + + + + + + + + + + +
Back: 19.7 Continuations and the C-interfaceForward: 21. Copyright and license   FastBack: 19. C-interfaceUp: Gambit-CFastForward: 21. Copyright and licenseTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

20. System limitations

+ + + + +
+ + + + + + + + + + + +
Back: 20. System limitationsForward: General index   FastBack: 20. System limitationsUp: Gambit-CFastForward: General indexTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

21. Copyright and license

+ +

The Gambit-C system release v4.6.1 is Copyright © +1994-2009 by Marc Feeley, all rights reserved. The Gambit-C system +release v4.6.1 is licensed under two licenses: the Apache +License, Version 2.0, and the GNU LESSER GENERAL PUBLIC LICENSE, +Version 2.1. You have the option to choose which of these two +licenses to abide by. The licenses are copied below. +

+ + +
 

+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+   To apply the Apache License to your work, attach the following
+   boilerplate notice, with the fields enclosed by brackets "[]"
+   replaced with your own identifying information. (Don't include
+   the brackets!)  The text should be enclosed in the appropriate
+   comment syntax for the file format. We also recommend that a
+   file or class name and description of purpose be included on the
+   same "printed page" as the copyright notice for easier
+   identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+ + + +
 
                  GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ + + +
 
  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ + + +
 
                  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ + + +
 
  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+ + + +
 
  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ + + +
 
  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ + + +
 
  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ + + +
 
  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                            NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+ + + +
 
           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+ + + +
+ + + + + + + + + + + +
Back: 21. Copyright and licenseForward: General index   FastBack: 21. Copyright and licenseUp: Gambit-CFastForward: General indexTop: Gambit-CContents: Table of ContentsIndex: General index
+ +

General index

+ +
Jump to:   # +   ++ +   +, +   +- +   +. +   +< +   += +   +> +   +^ +   +_ +   +| +   +~ +   +
+A +   +B +   +C +   +D +   +E +   +F +   +G +   +H +   +I +   +J +   +K +   +L +   +M +   +N +   +O +   +P +   +R +   +S +   +T +   +U +   +V +   +W +   +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Index Entry Section

#
#5.4 Procedures related to debugging
##5.4 Procedures related to debugging

+
+z3.4.4 Other compilation options

,
,(b expr)5.2 Debugging commands
,(be expr)5.2 Debugging commands
,(bed expr)5.2 Debugging commands
,(c expr)5.2 Debugging commands
,(e expr)5.2 Debugging commands
,(ed expr)5.2 Debugging commands
,(h subject)5.2 Debugging commands
,(st expr)5.2 Debugging commands
,(v expr)5.2 Debugging commands
,+5.2 Debugging commands
,++5.2 Debugging commands
,-5.2 Debugging commands
,--5.2 Debugging commands
,?5.2 Debugging commands
,b5.2 Debugging commands
,be5.2 Debugging commands
,bed5.2 Debugging commands
,c5.2 Debugging commands
,d5.2 Debugging commands
,e5.2 Debugging commands
,ed5.2 Debugging commands
,h5.2 Debugging commands
,i5.2 Debugging commands
,l5.2 Debugging commands
,N5.2 Debugging commands
,N+5.2 Debugging commands
,N-5.2 Debugging commands
,q5.2 Debugging commands
,qt5.2 Debugging commands
,s5.2 Debugging commands
,st5.2 Debugging commands
,t5.2 Debugging commands
,y5.2 Debugging commands

-
-3.3 Batch mode
-:+4. Runtime options
-:-4. Runtime options
-::4. Runtime options
-:=4. Runtime options
-:}4. Runtime options
-:d4. Runtime options
-:d-4. Runtime options
-:d@[HOST][:PORT]4. Runtime options
-:da4. Runtime options
-:dc4. Runtime options
-:dD4. Runtime options
-:di4. Runtime options
-:dLEVEL4. Runtime options
-:dp4. Runtime options
-:dQ4. Runtime options
-:dq4. Runtime options
-:dR4. Runtime options
-:dr4. Runtime options
-:ds4. Runtime options
-:f4. Runtime options
-:h4. Runtime options
-:l4. Runtime options
-:m4. Runtime options
-:S4. Runtime options
-:s4. Runtime options
-:s6.3 Miscellaneous extensions
-:t4. Runtime options
-:~~4. Runtime options
-c3.3 Batch mode
-call_shared3.4.4 Other compilation options
-cc-options3.3 Batch mode
-debug3.3 Batch mode
-debug6.3 Miscellaneous extensions
-debug-environments3.3 Batch mode
-debug-environments6.3 Miscellaneous extensions
-debug-location3.3 Batch mode
-debug-location6.3 Miscellaneous extensions
-debug-source3.3 Batch mode
-debug-source6.3 Miscellaneous extensions
-dynamic3.3 Batch mode
-D___DYNAMIC3.4.2 Building a loadable library
-D___LIBRARY3.4.3 Building a shared-library
-D___PRIMAL3.4.3 Building a shared-library
-D___SHARED3.4.3 Building a shared-library
-D___SINGLE_HOST3.4.4 Other compilation options
-e3.3 Batch mode
-exe3.3 Batch mode
-exe3.3 Batch mode
-expansion3.3 Batch mode
-flat3.3 Batch mode
-fPIC3.4.4 Other compilation options
-fpic3.4.4 Other compilation options
-G3.4.4 Other compilation options
-gvm3.3 Batch mode
-i3.3 Batch mode
-I/usr/local/Gambit-C/include3.4.4 Other compilation options
-keep-c3.3 Batch mode
-KPIC3.4.4 Other compilation options
-Kpic3.4.4 Other compilation options
-l base3.3 Batch mode
-L/usr/local/Gambit-C/lib3.4.4 Other compilation options
-ld-options3.3 Batch mode
-ld-options-prelude3.3 Batch mode
-link3.3 Batch mode
-link3.3 Batch mode
-O3.4.4 Other compilation options
-o output3.3 Batch mode
-obj3.3 Batch mode
-pic3.4.4 Other compilation options
-postlude3.3 Batch mode
-prelude3.3 Batch mode
-rdynamic3.4.4 Other compilation options
-report3.3 Batch mode
-shared3.4.4 Other compilation options
-track-scheme3.3 Batch mode
-verbose3.3 Batch mode
-warnings3.3 Batch mode

.
.c3.3 Batch mode
.scm3.3 Batch mode
.six3.3 Batch mode

<
<9.1 Extensions to numeric procedures
<=9.1 Extensions to numeric procedures

=
=9.1 Extensions to numeric procedures

>
>9.1 Extensions to numeric procedures
>=9.1 Extensions to numeric procedures

^
^C4. Runtime options
^C5.1 Debugging model
^D5.1 Debugging model

_
___cleanup19.5 The c-define special form
___setup19.5 The c-define special form

|
|six.x,y|6.4 Undocumented extensions
|six.x\|=y|6.4 Undocumented extensions
|six.x\|y|6.4 Undocumented extensions
|six.x\|\|y|6.4 Undocumented extensions

~
~16.1 Handling of file names
~username16.1 Handling of file names
~~16.1 Handling of file names

A
abandoned-mutex-exception?15.4 Exception objects related to threads
abort15.1 Exception-handling
absolute path16.1 Handling of file names
absolute path16.1 Handling of file names
address-info-family16.11 Host information
address-info-protocol16.11 Host information
address-info-socket-info16.11 Host information
address-info-socket-type16.11 Host information
address-info?16.11 Host information
address-infos16.11 Host information
all-bits-set?9.4 Bitwise-operations on exact integers
any-bits-set?9.4 Bitwise-operations on exact integers
append-f32vectors10. Homogeneous vectors
append-f64vectors10. Homogeneous vectors
append-s16vectors10. Homogeneous vectors
append-s32vectors10. Homogeneous vectors
append-s64vectors10. Homogeneous vectors
append-s8vectors10. Homogeneous vectors
append-strings6.3 Miscellaneous extensions
append-u16vectors10. Homogeneous vectors
append-u32vectors10. Homogeneous vectors
append-u64vectors10. Homogeneous vectors
append-u8vectors10. Homogeneous vectors
append-vectors6.3 Miscellaneous extensions
arithmetic-shift9.4 Bitwise-operations on exact integers

B
bit-count9.4 Bitwise-operations on exact integers
bit-set?9.4 Bitwise-operations on exact integers
bitwise-and9.4 Bitwise-operations on exact integers
bitwise-ior9.4 Bitwise-operations on exact integers
bitwise-merge9.4 Bitwise-operations on exact integers
bitwise-not9.4 Bitwise-operations on exact integers
bitwise-xor9.4 Bitwise-operations on exact integers
block6.3 Miscellaneous extensions
box6.3 Miscellaneous extensions
box?6.3 Miscellaneous extensions
boxes6.3 Miscellaneous extensions
break5.4 Procedures related to debugging

C
c-declare19.2 The c-declare special form
c-declare19.2 The c-declare special form
c-define19.5 The c-define special form
c-define19.5 The c-define special form
c-define-type19.6 The c-define-type special form
c-define-type19.6 The c-define-type special form
c-initialize19.3 The c-initialize special form
c-initialize19.3 The c-initialize special form
c-lambda19.4 The c-lambda special form
c-lambda19.4 The c-lambda special form
call-with-current-continuation6.1 Extensions to standard procedures
call-with-input-file17.7.1 Filesystem devices
call-with-input-process17.7.2 Process devices
call-with-input-string17.10 String-ports
call-with-input-u8vector17.11 U8vector-ports
call-with-input-vector17.9 Vector-ports
call-with-output-file17.7.1 Filesystem devices
call-with-output-process17.7.2 Process devices
call-with-output-string17.10 String-ports
call-with-output-u8vector17.11 U8vector-ports
call-with-output-vector17.9 Vector-ports
call/cc6.1 Extensions to standard procedures
central installation directory16.1 Handling of file names
cfun-conversion-exception-arguments15.5 Exception objects related to C-interface
cfun-conversion-exception-code15.5 Exception objects related to C-interface
cfun-conversion-exception-message15.5 Exception objects related to C-interface
cfun-conversion-exception-procedure15.5 Exception objects related to C-interface
cfun-conversion-exception?15.5 Exception objects related to C-interface
char->integer8.1 Extensions to character procedures
char-ci<=?8.1 Extensions to character procedures
char-ci<?8.1 Extensions to character procedures
char-ci=?8.1 Extensions to character procedures
char-ci>=?8.1 Extensions to character procedures
char-ci>?8.1 Extensions to character procedures
char<=?8.1 Extensions to character procedures
char<?8.1 Extensions to character procedures
char=?8.1 Extensions to character procedures
char>=?8.1 Extensions to character procedures
char>?8.1 Extensions to character procedures
clear-bit-field9.4 Bitwise-operations on exact integers
close-input-port17.4.2 Object-port operations
close-output-port17.4.2 Object-port operations
close-port17.4.2 Object-port operations
command-line2.5 Scheme scripts
command-line16.5 Command line arguments
compile-file3.5 Procedures specific to compiler
compile-file-to-c3.5 Procedures specific to compiler
compiler3. The Gambit Scheme compiler
compiler options3.3 Batch mode
cond-expand6.4 Undocumented extensions
condition-variable-broadcast!13.9 Procedures
condition-variable-name13.9 Procedures
condition-variable-signal!13.9 Procedures
condition-variable-specific13.9 Procedures
condition-variable-specific-set!13.9 Procedures
condition-variable?13.9 Procedures
configure-command-string6.4 Undocumented extensions
console-port6.4 Undocumented extensions
constant-fold6.3 Miscellaneous extensions
continuation-capture6.4 Undocumented extensions
continuation-graft6.4 Undocumented extensions
continuation-return6.4 Undocumented extensions
continuation?6.4 Undocumented extensions
continuations19.7 Continuations and the C-interface
copy-bit-field9.4 Bitwise-operations on exact integers
copy-file16.2 Filesystem operations
cpu-time16.7 Measuring time
create-directory16.2 Filesystem operations
create-fifo16.2 Filesystem operations
create-link16.2 Filesystem operations
create-symbolic-link16.2 Filesystem operations
current exception-handler15.1 Exception-handling
current working directory16.1 Handling of file names
current working directory16.1 Handling of file names
current-directory16.1 Handling of file names
current-error-port17.12 Other procedures related to I/O
current-exception-handler15.1 Exception-handling
current-input-port17.12 Other procedures related to I/O
current-output-port17.12 Other procedures related to I/O
current-readtable17.12 Other procedures related to I/O
current-thread13.9 Procedures
current-time16.7 Measuring time
current-user-interrupt-handler6.4 Undocumented extensions

D
datum-parsing-exception-kind15.6 Exception objects related to the reader
datum-parsing-exception-parameters15.6 Exception objects related to the reader
datum-parsing-exception-readenv15.6 Exception objects related to the reader
datum-parsing-exception?15.6 Exception objects related to the reader
deadlock-exception?15.4 Exception objects related to threads
debug3.3 Batch mode
debug6.3 Miscellaneous extensions
debug-environments3.3 Batch mode
debug-environments6.3 Miscellaneous extensions
debug-location3.3 Batch mode
debug-location6.3 Miscellaneous extensions
debug-source3.3 Batch mode
debug-source6.3 Miscellaneous extensions
declare6.3 Miscellaneous extensions
default-random-source9.7 Pseudo random numbers
defer-user-interrupts6.4 Undocumented extensions
define6.2 Extensions to standard special forms
define20. System limitations
define-cond-expand-feature6.4 Undocumented extensions
define-macro6.3 Miscellaneous extensions
define-record-type6.4 Undocumented extensions
define-structure12. Records
define-syntax6.3 Miscellaneous extensions
define-syntax6.3 Miscellaneous extensions
define-type6.4 Undocumented extensions
define-type-of-thread6.4 Undocumented extensions
delete-directory16.2 Filesystem operations
delete-file16.2 Filesystem operations
deserialization10. Homogeneous vectors
deserialization18.1 Readtables
directory-files16.2 Filesystem operations
display-continuation-backtrace6.4 Undocumented extensions
display-continuation-dynamic-environment6.4 Undocumented extensions
display-continuation-environment6.4 Undocumented extensions
display-dynamic-environment?5.4 Procedures related to debugging
display-environment-set!5.4 Procedures related to debugging
display-exception6.4 Undocumented extensions
display-exception-in-context6.4 Undocumented extensions
display-procedure-environment6.4 Undocumented extensions
divide-by-zero-exception-arguments15.8 Exception objects related to type checking
divide-by-zero-exception-procedure15.8 Exception objects related to type checking
divide-by-zero-exception?15.8 Exception objects related to type checking

E
Emacs5.6 Emacs interface
eq?-hash11.1 Hashing
equal?-hash11.1 Hashing
eqv?-hash11.1 Hashing
err-code->string6.4 Undocumented extensions
error15.10 Other exception objects
error-exception-message15.10 Other exception objects
error-exception-parameters15.10 Other exception objects
error-exception?15.10 Other exception objects
eval6.3 Miscellaneous extensions
exit16.4 Process termination
expression-parsing-exception-kind15.7 Exception objects related to evaluation and compilation
expression-parsing-exception-parameters15.7 Exception objects related to evaluation and compilation
expression-parsing-exception-source15.7 Exception objects related to evaluation and compilation
expression-parsing-exception?15.7 Exception objects related to evaluation and compilation
extended-bindings6.3 Miscellaneous extensions
extract-bit-field9.4 Bitwise-operations on exact integers

F
f32vector10. Homogeneous vectors
f32vector->list10. Homogeneous vectors
f32vector-append10. Homogeneous vectors
f32vector-copy10. Homogeneous vectors
f32vector-fill!10. Homogeneous vectors
f32vector-length10. Homogeneous vectors
f32vector-ref10. Homogeneous vectors
f32vector-set!10. Homogeneous vectors
f32vector-shrink!10. Homogeneous vectors
f32vector?10. Homogeneous vectors
f64vector10. Homogeneous vectors
f64vector->list10. Homogeneous vectors
f64vector-append10. Homogeneous vectors
f64vector-copy10. Homogeneous vectors
f64vector-fill!10. Homogeneous vectors
f64vector-length10. Homogeneous vectors
f64vector-ref10. Homogeneous vectors
f64vector-set!10. Homogeneous vectors
f64vector-shrink!10. Homogeneous vectors
f64vector?10. Homogeneous vectors
FFI19. C-interface
file names16.1 Handling of file names
file-attributes16.8 File information
file-creation-time16.8 File information
file-device16.8 File information
file-exists?16.8 File information
file-group16.8 File information
file-info16.8 File information
file-info-attributes16.8 File information
file-info-creation-time16.8 File information
file-info-device16.8 File information
file-info-group16.8 File information
file-info-inode16.8 File information
file-info-last-access-time16.8 File information
file-info-last-change-time16.8 File information
file-info-last-modification-time16.8 File information
file-info-mode16.8 File information
file-info-number-of-links16.8 File information
file-info-owner16.8 File information
file-info-size16.8 File information
file-info-type16.8 File information
file-info?16.8 File information
file-inode16.8 File information
file-last-access-time16.8 File information
file-last-change-time16.8 File information
file-last-modification-time16.8 File information
file-mode16.8 File information
file-number-of-links16.8 File information
file-owner16.8 File information
file-size16.8 File information
file-type16.8 File information
file.c3.3 Batch mode
file.scm3.3 Batch mode
file.six3.3 Batch mode
finite?6.4 Undocumented extensions
first-bit-set9.4 Bitwise-operations on exact integers
fixnum6.3 Miscellaneous extensions
fixnum->flonum9.6 Flonum specific operations
fixnum-overflow-exception-arguments9.5 Fixnum specific operations
fixnum-overflow-exception-procedure9.5 Fixnum specific operations
fixnum-overflow-exception?9.5 Fixnum specific operations
fixnum?9.5 Fixnum specific operations
fl*9.6 Flonum specific operations
fl+9.6 Flonum specific operations
fl-9.6 Flonum specific operations
fl/9.6 Flonum specific operations
fl<9.6 Flonum specific operations
fl<=9.6 Flonum specific operations
fl=9.6 Flonum specific operations
fl>9.6 Flonum specific operations
fl>=9.6 Flonum specific operations
flabs9.6 Flonum specific operations
flacos9.6 Flonum specific operations
flasin9.6 Flonum specific operations
flatan9.6 Flonum specific operations
flatan9.6 Flonum specific operations
flceiling9.6 Flonum specific operations
flcos9.6 Flonum specific operations
fldenominator9.6 Flonum specific operations
fleven?9.6 Flonum specific operations
flexp9.6 Flonum specific operations
flexpt9.6 Flonum specific operations
flfinite?9.6 Flonum specific operations
flfloor9.6 Flonum specific operations
flinfinite?9.6 Flonum specific operations
flinteger?9.6 Flonum specific operations
fllog9.6 Flonum specific operations
flmax9.6 Flonum specific operations
flmin9.6 Flonum specific operations
flnan?9.6 Flonum specific operations
flnegative?9.6 Flonum specific operations
flnumerator9.6 Flonum specific operations
floating point overflow20. System limitations
flodd?9.6 Flonum specific operations
flonum6.3 Miscellaneous extensions
flonum?9.6 Flonum specific operations
flpositive?9.6 Flonum specific operations
flround9.6 Flonum specific operations
flsin9.6 Flonum specific operations
flsqrt9.6 Flonum specific operations
fltan9.6 Flonum specific operations
fltruncate9.6 Flonum specific operations
flzero?9.6 Flonum specific operations
force-output17.4.2 Object-port operations
foreign function interface19. C-interface
foreign-address6.4 Undocumented extensions
foreign-release!6.4 Undocumented extensions
foreign-released?6.4 Undocumented extensions
foreign-tags6.4 Undocumented extensions
foreign?6.4 Undocumented extensions
future6.4 Undocumented extensions
fx*9.5 Fixnum specific operations
fx+9.5 Fixnum specific operations
fx-9.5 Fixnum specific operations
fx<9.5 Fixnum specific operations
fx<=9.5 Fixnum specific operations
fx=9.5 Fixnum specific operations
fx>9.5 Fixnum specific operations
fx>=9.5 Fixnum specific operations
fxabs9.5 Fixnum specific operations
fxand9.5 Fixnum specific operations
fxarithmetic-shift9.5 Fixnum specific operations
fxarithmetic-shift-left9.5 Fixnum specific operations
fxarithmetic-shift-right9.5 Fixnum specific operations
fxbit-count9.5 Fixnum specific operations
fxbit-set?9.5 Fixnum specific operations
fxeven?9.5 Fixnum specific operations
fxfirst-bit-set9.5 Fixnum specific operations
fxif9.5 Fixnum specific operations
fxior9.5 Fixnum specific operations
fxlength9.5 Fixnum specific operations
fxmax9.5 Fixnum specific operations
fxmin9.5 Fixnum specific operations
fxmodulo9.5 Fixnum specific operations
fxnegative?9.5 Fixnum specific operations
fxnot9.5 Fixnum specific operations
fxodd?9.5 Fixnum specific operations
fxpositive?9.5 Fixnum specific operations
fxquotient9.5 Fixnum specific operations
fxremainder9.5 Fixnum specific operations
fxwrap*9.5 Fixnum specific operations
fxwrap+9.5 Fixnum specific operations
fxwrap-9.5 Fixnum specific operations
fxwrapabs9.5 Fixnum specific operations
fxwraparithmetic-shift9.5 Fixnum specific operations
fxwraparithmetic-shift-left9.5 Fixnum specific operations
fxwraplogical-shift-right9.5 Fixnum specific operations
fxwrapquotient9.5 Fixnum specific operations
fxxor9.5 Fixnum specific operations
fxzero?9.5 Fixnum specific operations

G
GAMBCOPT, environment variable4. Runtime options
Gambit1. The Gambit-C system
Gambit-CGambit-C
Gambit-C1. The Gambit-C system
gambit-scheme6.3 Miscellaneous extensions
gambit.el5.6 Emacs interface
GC5.4 Procedures related to debugging
gc-report-set!5.4 Procedures related to debugging
generate-proper-tail-calls5.4 Procedures related to debugging
generic6.3 Miscellaneous extensions
gensym6.3 Miscellaneous extensions
get-output-string17.10 String-ports
get-output-u8vector17.11 U8vector-ports
get-output-vector17.9 Vector-ports
getenv16.6 Environment variables
group-info16.9 Group information
group-info-gid16.9 Group information
group-info-members16.9 Group information
group-info-name16.9 Group information
group-info?16.9 Group information
gsc1. The Gambit-C system
gsc3.3 Batch mode
gsc3.5 Procedures specific to compiler
gsc3.5 Procedures specific to compiler
gsc3.5 Procedures specific to compiler
gsc3.5 Procedures specific to compiler
gsc4. Runtime options
gsc-script2.5 Scheme scripts
gsi1. The Gambit-C system
gsi2. The Gambit Scheme interpreter
gsi4. Runtime options
gsi-script2.5 Scheme scripts

H
hashing11. Hashing and weak references
heap-overflow-exception?15.2 Exception objects related to memory management
help5.4 Procedures related to debugging
help-browser5.4 Procedures related to debugging
home directory16.1 Handling of file names
homogeneous vectors10. Homogeneous vectors
homogeneous vectors18.9 Homogeneous vector syntax
host-info16.11 Host information
host-info-addresses16.11 Host information
host-info-aliases16.11 Host information
host-info-name16.11 Host information
host-info?16.11 Host information
host-name16.11 Host information

I
ieee-scheme6.3 Miscellaneous extensions
improper-length-list-exception-arg-num15.8 Exception objects related to type checking
improper-length-list-exception-arguments15.8 Exception objects related to type checking
improper-length-list-exception-procedure15.8 Exception objects related to type checking
improper-length-list-exception?15.8 Exception objects related to type checking
inactive-thread-exception-arguments6.4 Undocumented extensions
inactive-thread-exception-procedure6.4 Undocumented extensions
inactive-thread-exception?6.4 Undocumented extensions
include6.3 Miscellaneous extensions
include6.3 Miscellaneous extensions
infinite?6.4 Undocumented extensions
initialized-thread-exception-arguments6.4 Undocumented extensions
initialized-thread-exception-procedure6.4 Undocumented extensions
initialized-thread-exception?6.4 Undocumented extensions
inline6.3 Miscellaneous extensions
inline-primitives6.3 Miscellaneous extensions
inlining-limit6.3 Miscellaneous extensions
input-port-byte-position17.7.1 Filesystem devices
input-port-bytes-buffered6.4 Undocumented extensions
input-port-char-position6.4 Undocumented extensions
input-port-characters-buffered6.4 Undocumented extensions
input-port-column17.5.2 Character-port operations
input-port-line17.5.2 Character-port operations
input-port-readtable17.5.2 Character-port operations
input-port-readtable-set!17.5.2 Character-port operations
input-port-timeout-set!17.4.2 Object-port operations
input-port?17.4.2 Object-port operations
installation directories16.1 Handling of file names
integer->char8.1 Extensions to character procedures
integer-length9.4 Bitwise-operations on exact integers
integer-nth-root9.3 Integer square root and nth root
integer-sqrt9.3 Integer square root and nth root
interpreter2. The Gambit Scheme interpreter
interpreter3. The Gambit Scheme compiler
interrupts-enabled6.3 Miscellaneous extensions
invalid-hash-number-exception-arguments6.4 Undocumented extensions
invalid-hash-number-exception-procedure6.4 Undocumented extensions
invalid-hash-number-exception?6.4 Undocumented extensions

J
join-timeout-exception-arguments15.4 Exception objects related to threads
join-timeout-exception-procedure15.4 Exception objects related to threads
join-timeout-exception?15.4 Exception objects related to threads

K
keyword->string6.3 Miscellaneous extensions
keyword-expected-exception-arguments15.9 Exception objects related to procedure call
keyword-expected-exception-procedure15.9 Exception objects related to procedure call
keyword-expected-exception?15.9 Exception objects related to procedure call
keyword-hash11.1 Hashing
keyword?6.3 Miscellaneous extensions
keywords6.3 Miscellaneous extensions

L
lambda6.2 Extensions to standard special forms
lambda-lift6.3 Miscellaneous extensions
last_.c3.3 Batch mode
limitations20. System limitations
link-flat3.5 Procedures specific to compiler
link-incremental3.5 Procedures specific to compiler
list->f32vector10. Homogeneous vectors
list->f64vector10. Homogeneous vectors
list->s16vector10. Homogeneous vectors
list->s32vector10. Homogeneous vectors
list->s64vector10. Homogeneous vectors
list->s8vector10. Homogeneous vectors
list->table11.2.2 Tables
list->u16vector10. Homogeneous vectors
list->u32vector10. Homogeneous vectors
list->u64vector10. Homogeneous vectors
list->u8vector10. Homogeneous vectors
load3.5 Procedures specific to compiler

M
mailbox-receive-timeout-exception-arguments13.9 Procedures
mailbox-receive-timeout-exception-procedure13.9 Procedures
mailbox-receive-timeout-exception?13.9 Procedures
main6.4 Undocumented extensions
make-condition-variable13.9 Procedures
make-f32vector10. Homogeneous vectors
make-f64vector10. Homogeneous vectors
make-mutex13.9 Procedures
make-parameter14. Dynamic environment
make-random-source9.7 Pseudo random numbers
make-root-thread13.9 Procedures
make-s16vector10. Homogeneous vectors
make-s32vector10. Homogeneous vectors
make-s64vector10. Homogeneous vectors
make-s8vector10. Homogeneous vectors
make-table11.2.2 Tables
make-thread13.9 Procedures
make-thread-group6.4 Undocumented extensions
make-u16vector10. Homogeneous vectors
make-u32vector10. Homogeneous vectors
make-u64vector10. Homogeneous vectors
make-u8vector10. Homogeneous vectors
make-uninterned-keyword6.3 Miscellaneous extensions
make-uninterned-symbol6.3 Miscellaneous extensions
make-will11.2.1 Wills
mostly-fixnum6.3 Miscellaneous extensions
mostly-fixnum-flonum6.3 Miscellaneous extensions
mostly-flonum6.3 Miscellaneous extensions
mostly-flonum-fixnum6.3 Miscellaneous extensions
mostly-generic6.3 Miscellaneous extensions
multiple-c-return-exception?15.5 Exception objects related to C-interface
mutex-lock!13.9 Procedures
mutex-name13.9 Procedures
mutex-specific13.9 Procedures
mutex-specific-set!13.9 Procedures
mutex-state13.9 Procedures
mutex-unlock!13.9 Procedures
mutex?13.9 Procedures

N
namespace6.4 Undocumented extensions
nan?6.4 Undocumented extensions
network-info16.14 Network information
network-info-aliases16.14 Network information
network-info-name16.14 Network information
network-info-number16.14 Network information
network-info?16.14 Network information
newline17.4.2 Object-port operations
no-such-file-or-directory-exception-arguments15.3 Exception objects related to the host environment
no-such-file-or-directory-exception-procedure15.3 Exception objects related to the host environment
no-such-file-or-directory-exception?15.3 Exception objects related to the host environment
noncontinuable-exception-reason15.1 Exception-handling
noncontinuable-exception?15.1 Exception-handling
nonempty-input-port-character-buffer-exception-arguments6.4 Undocumented extensions
nonempty-input-port-character-buffer-exception-procedure6.4 Undocumented extensions
nonempty-input-port-character-buffer-exception?6.4 Undocumented extensions
nonprocedure-operator-exception-arguments15.9 Exception objects related to procedure call
nonprocedure-operator-exception-code15.9 Exception objects related to procedure call
nonprocedure-operator-exception-operator15.9 Exception objects related to procedure call
nonprocedure-operator-exception-rte15.9 Exception objects related to procedure call
nonprocedure-operator-exception?15.9 Exception objects related to procedure call
normalized path16.1 Handling of file names
number-of-arguments-limit-exception-arguments15.9 Exception objects related to procedure call
number-of-arguments-limit-exception-procedure15.9 Exception objects related to procedure call
number-of-arguments-limit-exception?15.9 Exception objects related to procedure call

O
object file3.5 Procedures specific to compiler
object->serial-number11.1 Hashing
object->string17.10 String-ports
object->u8vector10. Homogeneous vectors
open-directory17.8 Directory-ports
open-dummy6.4 Undocumented extensions
open-event-queue6.4 Undocumented extensions
open-file17.7.1 Filesystem devices
open-input-file17.7.1 Filesystem devices
open-input-process17.7.2 Process devices
open-input-string17.10 String-ports
open-input-u8vector17.11 U8vector-ports
open-input-vector17.9 Vector-ports
open-output-file17.7.1 Filesystem devices
open-output-process17.7.2 Process devices
open-output-string17.10 String-ports
open-output-u8vector17.11 U8vector-ports
open-output-vector17.9 Vector-ports
open-process17.7.2 Process devices
open-string17.10 String-ports
open-string-pipe17.10 String-ports
open-tcp-client17.7.3 Network devices
open-tcp-server17.7.3 Network devices
open-u8vector17.11 U8vector-ports
open-u8vector-pipe17.11 U8vector-ports
open-vector17.9 Vector-ports
open-vector-pipe17.9 Vector-ports
optimize-dead-local-variables6.3 Miscellaneous extensions
options, compiler3.3 Batch mode
options, runtime4. Runtime options
os-exception-arguments15.3 Exception objects related to the host environment
os-exception-code15.3 Exception objects related to the host environment
os-exception-message15.3 Exception objects related to the host environment
os-exception-procedure15.3 Exception objects related to the host environment
os-exception?15.3 Exception objects related to the host environment
output-port-byte-position17.7.1 Filesystem devices
output-port-char-position6.4 Undocumented extensions
output-port-column17.5.2 Character-port operations
output-port-line17.5.2 Character-port operations
output-port-readtable17.5.2 Character-port operations
output-port-readtable-set!17.5.2 Character-port operations
output-port-timeout-set!17.4.2 Object-port operations
output-port-width17.5.2 Character-port operations
output-port?17.4.2 Object-port operations
overflow, floating point20. System limitations

P
parameterize14. Dynamic environment
path-directory16.1 Handling of file names
path-expand16.1 Handling of file names
path-extension16.1 Handling of file names
path-normalize16.1 Handling of file names
path-strip-directory16.1 Handling of file names
path-strip-extension16.1 Handling of file names
path-strip-trailing-directory-separator16.1 Handling of file names
path-strip-volume16.1 Handling of file names
path-volume16.1 Handling of file names
peek-char17.5.2 Character-port operations
port-settings-set!6.4 Undocumented extensions
port?17.4.2 Object-port operations
pp5.4 Procedures related to debugging
pretty-print5.4 Procedures related to debugging
primordial-exception-handler6.4 Undocumented extensions
print17.12 Other procedures related to I/O
println17.12 Other procedures related to I/O
process-pid17.7.2 Process devices
process-status17.7.2 Process devices
process-times16.7 Measuring time
proper tail-calls5.4 Procedures related to debugging
proper tail-calls6.3 Miscellaneous extensions
proper-tail-calls6.3 Miscellaneous extensions
protocol-info16.13 Protocol information
protocol-info-aliases16.13 Protocol information
protocol-info-name16.13 Protocol information
protocol-info-number16.13 Protocol information
protocol-info?16.13 Protocol information

R
r4rs-scheme6.3 Miscellaneous extensions
r5rs-scheme6.3 Miscellaneous extensions
raise15.1 Exception-handling
random-f64vector9.7 Pseudo random numbers
random-integer9.7 Pseudo random numbers
random-real9.7 Pseudo random numbers
random-source-make-f64vectors9.7 Pseudo random numbers
random-source-make-integers9.7 Pseudo random numbers
random-source-make-reals9.7 Pseudo random numbers
random-source-make-u8vectors9.7 Pseudo random numbers
random-source-pseudo-randomize!9.7 Pseudo random numbers
random-source-randomize!9.7 Pseudo random numbers
random-source-state-ref9.7 Pseudo random numbers
random-source-state-set!9.7 Pseudo random numbers
random-source?9.7 Pseudo random numbers
random-u8vector9.7 Pseudo random numbers
range-exception-arg-num15.8 Exception objects related to type checking
range-exception-arguments15.8 Exception objects related to type checking
range-exception-procedure15.8 Exception objects related to type checking
range-exception?15.8 Exception objects related to type checking
read17.4.2 Object-port operations
read-all17.4.2 Object-port operations
read-char17.5.2 Character-port operations
read-line17.5.2 Character-port operations
read-substring17.5.2 Character-port operations
read-subu8vector17.6.2 Byte-port operations
read-u817.6.2 Byte-port operations
readtable-case-conversion?18.1 Readtables
readtable-case-conversion?-set18.1 Readtables
readtable-eval-allowed?18.1 Readtables
readtable-eval-allowed?-set18.1 Readtables
readtable-keywords-allowed?18.1 Readtables
readtable-keywords-allowed?-set18.1 Readtables
readtable-max-unescaped-char18.1 Readtables
readtable-max-unescaped-char-set18.1 Readtables
readtable-max-write-length18.1 Readtables
readtable-max-write-length-set18.1 Readtables
readtable-max-write-level18.1 Readtables
readtable-max-write-level-set18.1 Readtables
readtable-sharing-allowed?18.1 Readtables
readtable-sharing-allowed?-set18.1 Readtables
readtable-start-syntax18.1 Readtables
readtable-start-syntax-set18.1 Readtables
readtable-write-cdr-read-macros?18.1 Readtables
readtable-write-cdr-read-macros?-set18.1 Readtables
readtable-write-extended-read-macros?18.1 Readtables
readtable-write-extended-read-macros?-set18.1 Readtables
readtable?18.1 Readtables
real-time16.7 Measuring time
receive6.4 Undocumented extensions
relative path16.1 Handling of file names
relative path16.1 Handling of file names
rename-file16.2 Filesystem operations
repl-display-environment?5.4 Procedures related to debugging
repl-input-port6.4 Undocumented extensions
repl-output-port6.4 Undocumented extensions
repl-result-history-max-length-set!5.4 Procedures related to debugging
repl-result-history-ref5.4 Procedures related to debugging
replace-bit-field9.4 Bitwise-operations on exact integers
rpc-remote-error-exception-arguments6.4 Undocumented extensions
rpc-remote-error-exception-message6.4 Undocumented extensions
rpc-remote-error-exception-procedure6.4 Undocumented extensions
rpc-remote-error-exception?6.4 Undocumented extensions
run-time-bindings6.3 Miscellaneous extensions
runtime options4. Runtime options

S
s16vector10. Homogeneous vectors
s16vector->list10. Homogeneous vectors
s16vector-append10. Homogeneous vectors
s16vector-copy10. Homogeneous vectors
s16vector-fill!10. Homogeneous vectors
s16vector-length10. Homogeneous vectors
s16vector-ref10. Homogeneous vectors
s16vector-set!10. Homogeneous vectors
s16vector-shrink!10. Homogeneous vectors
s16vector?10. Homogeneous vectors
s32vector10. Homogeneous vectors
s32vector->list10. Homogeneous vectors
s32vector-append10. Homogeneous vectors
s32vector-copy10. Homogeneous vectors
s32vector-fill!10. Homogeneous vectors
s32vector-length10. Homogeneous vectors
s32vector-ref10. Homogeneous vectors
s32vector-set!10. Homogeneous vectors
s32vector-shrink!10. Homogeneous vectors
s32vector?10. Homogeneous vectors
s64vector10. Homogeneous vectors
s64vector->list10. Homogeneous vectors
s64vector-append10. Homogeneous vectors
s64vector-copy10. Homogeneous vectors
s64vector-fill!10. Homogeneous vectors
s64vector-length10. Homogeneous vectors
s64vector-ref10. Homogeneous vectors
s64vector-set!10. Homogeneous vectors
s64vector-shrink!10. Homogeneous vectors
s64vector?10. Homogeneous vectors
s8vector10. Homogeneous vectors
s8vector->list10. Homogeneous vectors
s8vector-append10. Homogeneous vectors
s8vector-copy10. Homogeneous vectors
s8vector-fill!10. Homogeneous vectors
s8vector-length10. Homogeneous vectors
s8vector-ref10. Homogeneous vectors
s8vector-set!10. Homogeneous vectors
s8vector-shrink!10. Homogeneous vectors
s8vector?10. Homogeneous vectors
safe6.3 Miscellaneous extensions
scheduler-exception-reason15.4 Exception objects related to threads
scheduler-exception?15.4 Exception objects related to threads
Scheme1. The Gambit-C system
Scheme, implementation ofGambit-C
scheme-ieee-1178-19902.5 Scheme scripts
scheme-r4rs2.5 Scheme scripts
scheme-r5rs2.5 Scheme scripts
scheme-srfi-02.5 Scheme scripts
seconds->time16.7 Measuring time
separate6.3 Miscellaneous extensions
serial-number->object11.1 Hashing
serialization10. Homogeneous vectors
serialization18.1 Readtables
service-info16.12 Service information
service-info-aliases16.12 Service information
service-info-name16.12 Service information
service-info-port-number16.12 Service information
service-info-protocol16.12 Service information
service-info?16.12 Service information
set!20. System limitations
set-box!6.3 Miscellaneous extensions
setenv16.6 Environment variables
sfun-conversion-exception-arguments15.5 Exception objects related to C-interface
sfun-conversion-exception-code15.5 Exception objects related to C-interface
sfun-conversion-exception-message15.5 Exception objects related to C-interface
sfun-conversion-exception-procedure15.5 Exception objects related to C-interface
sfun-conversion-exception?15.5 Exception objects related to C-interface
shell-command16.3 Shell command execution
six-script2.5 Scheme scripts
six.!6.4 Undocumented extensions
six.!x6.4 Undocumented extensions
six.&x6.4 Undocumented extensions
six.*x6.4 Undocumented extensions
six.++x6.4 Undocumented extensions
six.+x6.4 Undocumented extensions
six.--x6.4 Undocumented extensions
six.-x6.4 Undocumented extensions
six.arrow6.4 Undocumented extensions
six.break6.4 Undocumented extensions
six.call6.4 Undocumented extensions
six.case6.4 Undocumented extensions
six.clause6.4 Undocumented extensions
six.compound6.4 Undocumented extensions
six.cons6.4 Undocumented extensions
six.continue6.4 Undocumented extensions
six.define-procedure6.4 Undocumented extensions
six.define-variable6.4 Undocumented extensions
six.do-while6.4 Undocumented extensions
six.dot6.4 Undocumented extensions
six.for6.4 Undocumented extensions
six.goto6.4 Undocumented extensions
six.identifier6.4 Undocumented extensions
six.if6.4 Undocumented extensions
six.index6.4 Undocumented extensions
six.label6.4 Undocumented extensions
six.list6.4 Undocumented extensions
six.literal6.4 Undocumented extensions
six.make-array6.4 Undocumented extensions
six.new6.4 Undocumented extensions
six.null6.4 Undocumented extensions
six.prefix6.4 Undocumented extensions
six.procedure6.4 Undocumented extensions
six.procedure-body6.4 Undocumented extensions
six.return6.4 Undocumented extensions
six.switch6.4 Undocumented extensions
six.while6.4 Undocumented extensions
six.x!=y6.4 Undocumented extensions
six.x%=y6.4 Undocumented extensions
six.x%y6.4 Undocumented extensions
six.x&&y6.4 Undocumented extensions
six.x&=y6.4 Undocumented extensions
six.x&y6.4 Undocumented extensions
six.x*=y6.4 Undocumented extensions
six.x*y6.4 Undocumented extensions
six.x++6.4 Undocumented extensions
six.x+=y6.4 Undocumented extensions
six.x+y6.4 Undocumented extensions
six.x--6.4 Undocumented extensions
six.x-=y6.4 Undocumented extensions
six.x-y6.4 Undocumented extensions
six.x/=y6.4 Undocumented extensions
six.x/y6.4 Undocumented extensions
six.x:-y6.4 Undocumented extensions
six.x:=y6.4 Undocumented extensions
six.x:y6.4 Undocumented extensions
six.x<<=y6.4 Undocumented extensions
six.x<<y6.4 Undocumented extensions
six.x<=y6.4 Undocumented extensions
six.x<y6.4 Undocumented extensions
six.x==y6.4 Undocumented extensions
six.x=y6.4 Undocumented extensions
six.x>=y6.4 Undocumented extensions
six.x>>=y6.4 Undocumented extensions
six.x>>y6.4 Undocumented extensions
six.x>y6.4 Undocumented extensions
six.x?y:z6.4 Undocumented extensions
six.x^=y6.4 Undocumented extensions
six.x^y6.4 Undocumented extensions
six.~x6.4 Undocumented extensions
socket-info-address6.4 Undocumented extensions
socket-info-family6.4 Undocumented extensions
socket-info-port-number6.4 Undocumented extensions
socket-info?6.4 Undocumented extensions
stack-overflow-exception?15.2 Exception objects related to memory management
standard-bindings6.3 Miscellaneous extensions
started-thread-exception-arguments15.4 Exception objects related to threads
started-thread-exception-procedure15.4 Exception objects related to threads
started-thread-exception?15.4 Exception objects related to threads
step5.4 Procedures related to debugging
step-level-set!5.4 Procedures related to debugging
string->keyword6.3 Miscellaneous extensions
string-ci<=?8.2 Extensions to string procedures
string-ci<?8.2 Extensions to string procedures
string-ci=?8.2 Extensions to string procedures
string-ci=?-hash11.1 Hashing
string-ci>=?8.2 Extensions to string procedures
string-ci>?8.2 Extensions to string procedures
string-shrink!6.3 Miscellaneous extensions
string<=?8.2 Extensions to string procedures
string<?8.2 Extensions to string procedures
string=?8.2 Extensions to string procedures
string=?-hash11.1 Hashing
string>=?8.2 Extensions to string procedures
string>?8.2 Extensions to string procedures
subf32vector10. Homogeneous vectors
subf32vector-fill!10. Homogeneous vectors
subf32vector-move!10. Homogeneous vectors
subf64vector10. Homogeneous vectors
subf64vector-fill!10. Homogeneous vectors
subf64vector-move!10. Homogeneous vectors
subs16vector10. Homogeneous vectors
subs16vector-fill!10. Homogeneous vectors
subs16vector-move!10. Homogeneous vectors
subs32vector10. Homogeneous vectors
subs32vector-fill!10. Homogeneous vectors
subs32vector-move!10. Homogeneous vectors
subs64vector10. Homogeneous vectors
subs64vector-fill!10. Homogeneous vectors
subs64vector-move!10. Homogeneous vectors
subs8vector10. Homogeneous vectors
subs8vector-fill!10. Homogeneous vectors
subs8vector-move!10. Homogeneous vectors
substring-fill!6.3 Miscellaneous extensions
substring-move!6.3 Miscellaneous extensions
subu16vector10. Homogeneous vectors
subu16vector-fill!10. Homogeneous vectors
subu16vector-move!10. Homogeneous vectors
subu32vector10. Homogeneous vectors
subu32vector-fill!10. Homogeneous vectors
subu32vector-move!10. Homogeneous vectors
subu64vector10. Homogeneous vectors
subu64vector-fill!10. Homogeneous vectors
subu64vector-move!10. Homogeneous vectors
subu8vector10. Homogeneous vectors
subu8vector-fill!10. Homogeneous vectors
subu8vector-move!10. Homogeneous vectors
subvector6.3 Miscellaneous extensions
subvector-fill!6.3 Miscellaneous extensions
subvector-move!6.3 Miscellaneous extensions
symbol-hash11.1 Hashing
syntax-case6.3 Miscellaneous extensions
syntax-rules6.3 Miscellaneous extensions
system-stamp6.4 Undocumented extensions
system-type6.4 Undocumented extensions
system-type-string6.4 Undocumented extensions
system-version6.4 Undocumented extensions
system-version-string6.4 Undocumented extensions

T
table->list11.2.2 Tables
table-copy11.2.2 Tables
table-for-each11.2.2 Tables
table-length11.2.2 Tables
table-merge11.2.2 Tables
table-merge!11.2.2 Tables
table-ref11.2.2 Tables
table-search11.2.2 Tables
table-set!11.2.2 Tables
table?11.2.2 Tables
tables11. Hashing and weak references
tail-calls5.4 Procedures related to debugging
tail-calls6.3 Miscellaneous extensions
tcp-client-peer-socket-info6.4 Undocumented extensions
tcp-client-self-socket-info6.4 Undocumented extensions
tcp-server-socket-info6.4 Undocumented extensions
tcp-service-register!17.7.3 Network devices
tcp-service-unregister!17.7.3 Network devices
terminated-thread-exception-arguments15.4 Exception objects related to threads
terminated-thread-exception-procedure15.4 Exception objects related to threads
terminated-thread-exception?15.4 Exception objects related to threads
test-bit-field?9.4 Bitwise-operations on exact integers
this-source-file6.4 Undocumented extensions
thread-base-priority13.9 Procedures
thread-base-priority-set!13.9 Procedures
thread-group->thread-group-list6.4 Undocumented extensions
thread-group->thread-group-vector6.4 Undocumented extensions
thread-group->thread-list6.4 Undocumented extensions
thread-group->thread-vector6.4 Undocumented extensions
thread-group-name6.4 Undocumented extensions
thread-group-parent6.4 Undocumented extensions
thread-group-resume!6.4 Undocumented extensions
thread-group-suspend!6.4 Undocumented extensions
thread-group-terminate!6.4 Undocumented extensions
thread-group?6.4 Undocumented extensions
thread-init!6.4 Undocumented extensions
thread-interrupt!6.4 Undocumented extensions
thread-join!13.9 Procedures
thread-mailbox-extract-and-rewind13.9 Procedures
thread-mailbox-next13.9 Procedures
thread-mailbox-rewind13.9 Procedures
thread-name13.9 Procedures
thread-priority-boost13.9 Procedures
thread-priority-boost-set!13.9 Procedures
thread-quantum13.9 Procedures
thread-quantum-set!13.9 Procedures
thread-receive13.9 Procedures
thread-resume!6.4 Undocumented extensions
thread-send13.9 Procedures
thread-sleep!13.9 Procedures
thread-specific13.9 Procedures
thread-specific-set!13.9 Procedures
thread-start!13.9 Procedures
thread-state6.4 Undocumented extensions
thread-state-abnormally-terminated-reason6.4 Undocumented extensions
thread-state-abnormally-terminated?6.4 Undocumented extensions
thread-state-active-timeout6.4 Undocumented extensions
thread-state-active-waiting-for6.4 Undocumented extensions
thread-state-active?6.4 Undocumented extensions
thread-state-initialized?6.4 Undocumented extensions
thread-state-normally-terminated-result6.4 Undocumented extensions
thread-state-normally-terminated?6.4 Undocumented extensions
thread-state-uninitialized?6.4 Undocumented extensions
thread-suspend!6.4 Undocumented extensions
thread-terminate!13.9 Procedures
thread-thread-group6.4 Undocumented extensions
thread-yield!13.9 Procedures
thread?13.9 Procedures
threads13. Threads
time16.7 Measuring time
time->seconds16.7 Measuring time
time?16.7 Measuring time
timeout->time6.4 Undocumented extensions
top6.4 Undocumented extensions
touch6.4 Undocumented extensions
trace5.4 Procedures related to debugging
transcript-off6.1 Extensions to standard procedures
transcript-on6.1 Extensions to standard procedures
tty-history6.4 Undocumented extensions
tty-history-max-length-set!6.4 Undocumented extensions
tty-history-set!6.4 Undocumented extensions
tty-mode-set!6.4 Undocumented extensions
tty-paren-balance-duration-set!6.4 Undocumented extensions
tty-text-attributes-set!6.4 Undocumented extensions
tty-type-set!6.4 Undocumented extensions
tty?6.4 Undocumented extensions
type-exception-arg-num15.8 Exception objects related to type checking
type-exception-arguments15.8 Exception objects related to type checking
type-exception-procedure15.8 Exception objects related to type checking
type-exception-type-id15.8 Exception objects related to type checking
type-exception?15.8 Exception objects related to type checking

U
u16vector10. Homogeneous vectors
u16vector->list10. Homogeneous vectors
u16vector-append10. Homogeneous vectors
u16vector-copy10. Homogeneous vectors
u16vector-fill!10. Homogeneous vectors
u16vector-length10. Homogeneous vectors
u16vector-ref10. Homogeneous vectors
u16vector-set!10. Homogeneous vectors
u16vector-shrink!10. Homogeneous vectors
u16vector?10. Homogeneous vectors
u32vector10. Homogeneous vectors
u32vector->list10. Homogeneous vectors
u32vector-append10. Homogeneous vectors
u32vector-copy10. Homogeneous vectors
u32vector-fill!10. Homogeneous vectors
u32vector-length10. Homogeneous vectors
u32vector-ref10. Homogeneous vectors
u32vector-set!10. Homogeneous vectors
u32vector-shrink!10. Homogeneous vectors
u32vector?10. Homogeneous vectors
u64vector10. Homogeneous vectors
u64vector->list10. Homogeneous vectors
u64vector-append10. Homogeneous vectors
u64vector-copy10. Homogeneous vectors
u64vector-fill!10. Homogeneous vectors
u64vector-length10. Homogeneous vectors
u64vector-ref10. Homogeneous vectors
u64vector-set!10. Homogeneous vectors
u64vector-shrink!10. Homogeneous vectors
u64vector?10. Homogeneous vectors
u8vector10. Homogeneous vectors
u8vector->list10. Homogeneous vectors
u8vector->object10. Homogeneous vectors
u8vector-append10. Homogeneous vectors
u8vector-copy10. Homogeneous vectors
u8vector-fill!10. Homogeneous vectors
u8vector-length10. Homogeneous vectors
u8vector-ref10. Homogeneous vectors
u8vector-set!10. Homogeneous vectors
u8vector-shrink!10. Homogeneous vectors
u8vector?10. Homogeneous vectors
unbound-global-exception-code15.7 Exception objects related to evaluation and compilation
unbound-global-exception-rte15.7 Exception objects related to evaluation and compilation
unbound-global-exception-variable15.7 Exception objects related to evaluation and compilation
unbound-global-exception?15.7 Exception objects related to evaluation and compilation
unbound-os-environment-variable-exception-arguments15.3 Exception objects related to the host environment
unbound-os-environment-variable-exception-procedure15.3 Exception objects related to the host environment
unbound-os-environment-variable-exception?15.3 Exception objects related to the host environment
unbound-serial-number-exception-arguments11.1 Hashing
unbound-serial-number-exception-procedure11.1 Hashing
unbound-serial-number-exception?11.1 Hashing
unbound-table-key-exception-arguments11.2.2 Tables
unbound-table-key-exception-procedure11.2.2 Tables
unbound-table-key-exception?11.2.2 Tables
unbox6.3 Miscellaneous extensions
unbreak5.4 Procedures related to debugging
uncaught-exception-arguments15.4 Exception objects related to threads
uncaught-exception-procedure15.4 Exception objects related to threads
uncaught-exception-reason15.4 Exception objects related to threads
uncaught-exception?15.4 Exception objects related to threads
uninitialized-thread-exception-arguments6.4 Undocumented extensions
uninitialized-thread-exception-procedure6.4 Undocumented extensions
uninitialized-thread-exception?6.4 Undocumented extensions
uninterned-keyword?6.3 Miscellaneous extensions
uninterned-symbol?6.3 Miscellaneous extensions
unknown-keyword-argument-exception-arguments15.9 Exception objects related to procedure call
unknown-keyword-argument-exception-procedure15.9 Exception objects related to procedure call
unknown-keyword-argument-exception?15.9 Exception objects related to procedure call
unterminated-process-exception-arguments17.7.2 Process devices
unterminated-process-exception-procedure17.7.2 Process devices
unterminated-process-exception?17.7.2 Process devices
untrace5.4 Procedures related to debugging
user-info16.10 User information
user-info-gid16.10 User information
user-info-home16.10 User information
user-info-name16.10 User information
user-info-shell16.10 User information
user-info-uid16.10 User information
user-info?16.10 User information
user-name16.10 User information

V
vector-append6.3 Miscellaneous extensions
vector-copy6.3 Miscellaneous extensions
vector-shrink!6.3 Miscellaneous extensions
void6.3 Miscellaneous extensions

W
weak references11. Hashing and weak references
will-execute!11.2.1 Wills
will-testator11.2.1 Wills
will?11.2.1 Wills
with-exception-catcher15.1 Exception-handling
with-exception-handler15.1 Exception-handling
with-input-from-file17.7.1 Filesystem devices
with-input-from-port6.4 Undocumented extensions
with-input-from-process17.7.2 Process devices
with-input-from-string17.10 String-ports
with-input-from-u8vector17.11 U8vector-ports
with-input-from-vector17.9 Vector-ports
with-output-to-file17.7.1 Filesystem devices
with-output-to-port6.4 Undocumented extensions
with-output-to-process17.7.2 Process devices
with-output-to-string17.10 String-ports
with-output-to-u8vector17.11 U8vector-ports
with-output-to-vector17.9 Vector-ports
write17.4.2 Object-port operations
write-char17.5.2 Character-port operations
write-substring17.5.2 Character-port operations
write-subu8vector17.6.2 Byte-port operations
write-u817.6.2 Byte-port operations
wrong-number-of-arguments-exception-arguments15.9 Exception objects related to procedure call
wrong-number-of-arguments-exception-procedure15.9 Exception objects related to procedure call
wrong-number-of-arguments-exception?15.9 Exception objects related to procedure call

+
Jump to:   # +   ++ +   +, +   +- +   +. +   +< +   += +   +> +   +^ +   +_ +   +| +   +~ +   +
+A +   +B +   +C +   +D +   +E +   +F +   +G +   +H +   +I +   +J +   +K +   +L +   +M +   +N +   +O +   +P +   +R +   +S +   +T +   +U +   +V +   +W +   +
+ +
+ + + + + +
Top: Gambit-CContents: Table of ContentsIndex: General index
+

Table of Contents

+
+ + +
+ + + diff --git a/examples/iOS/help.html b/examples/iOS/help.html new file mode 100644 index 000000000..49f337952 --- /dev/null +++ b/examples/iOS/help.html @@ -0,0 +1,100 @@ + + + + + + + + + + + + +

+Gambit REPL is an interpreter for the Scheme programming language which closely conforms to the Scheme standard and also provides a large number of extensions. The following documents define the R5RS Scheme language and the extensions specific to the Gambit system, on which Gambit REPL is based. +

+ + + + + +

+Gambit REPL's user interface provides 4 views which are selectable with the tabs at the bottom of the screen. The views can be switched from portrait to landscape by turning the device. The landscape layout is recommended on iPhone, as it gives a keyboard with wider keys and text output with fewer line breaks. +

+ + + +

+The following predefined procedures are specific to Gambit REPL. +

+ + + +

+The Scheme file I/O procedures will read and write files in an area specific to the Gambit REPL app. The path "~" refers to the Documents folder. It is a convenient place to store files. This folder is initially empty. The content of the folder will be preserved when you update Gambit REPL to a newer version. The path "~~" refers to the Gambit REPL app bundle. +

+ + + + diff --git a/examples/iOS/html.scm b/examples/iOS/html.scm index 60f431eab..38f3aa384 100644 --- a/examples/iOS/html.scm +++ b/examples/iOS/html.scm @@ -319,12 +319,13 @@ port) (loop (+ end 1) (+ end 1)))))) (else + #; (display (string-append "Warning: Character (integer->char " (number->string index) ") is not a valid HTML 4.0 character entity\n") - (current-error-port)) + (repl-output-port)) (loop start (+ end 1))))))))))) ) diff --git a/examples/iOS/intf#.scm b/examples/iOS/intf#.scm new file mode 100644 index 000000000..2f6121aea --- /dev/null +++ b/examples/iOS/intf#.scm @@ -0,0 +1,115 @@ +;;;============================================================================ + +;;; File: "intf#.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("intf#" + +string->Class +Class->string +string->SEL +SEL->string +send0 +send1 +send2 +id->string +string->id +id->bool +bool->id +id->int +int->id +id->float +float->id +id->double +double->id + +NSDate +alloc +init +description +date + +NSBundle +mainBundle +objectForInfoDictionaryKey +mainBundle-info +CFBundleName +CFBundleDisplayName + +currentDevice-batteryLevel +currentDevice-batteryMonitoringEnabled +currentDevice-batteryMonitoringEnabled-set! +currentDevice-multitaskingSupported +currentDevice-model +currentDevice-name +currentDevice-systemName +currentDevice-systemVersion +currentDevice-uniqueIdentifier +device-status +device-model +UDID + +AudioServicesPlayAlertSound +AudioServicesPlaySystemSound +kSystemSoundID_FlashScreen +kSystemSoundID_Vibrate +kSystemSoundID_UserPreferredAlert + +set-navigation +show-cancelButton +hide-cancelButton +show-textView +show-webView +set-textView-font +set-textView-content +get-textView-content +add-output-to-textView +add-input-to-textView +set-webView-content +set-webView-content-from-file +eval-js-in-webView + +open-URL +segm-ctrl-set-title +segm-ctrl-insert +set-pref +get-pref +set-pasteboard +get-pasteboard +popup-alert + +send-input +send-event +send-key +handle-key +heartbeat +next-heartbeat-interval +interval-runnable +interval-io-pending +interval-no-io-pending +interval-min-wait + +eval-string + +repl-port +event-port +event-handler + +set-event-handler +show-view +set-view-content +set-page +set-page-content + +has-prefix? +get-event-parameters + +contained-path-resolve +app-dir + +)) + +;;;============================================================================ diff --git a/examples/iOS/intf.h b/examples/iOS/intf.h new file mode 100644 index 000000000..b7cdaccea --- /dev/null +++ b/examples/iOS/intf.h @@ -0,0 +1,16 @@ +/* File: "intf.h" */ + +/* + * Scheme functions which can be called from C. These functions are + * declared with a c-define in "intf.scm". + */ + +extern NSString *eval_string(NSString *); + +extern void send_input(NSString *); + +extern void send_event(NSString *); + +extern void send_key(NSString *); + +extern double heartbeat(); diff --git a/examples/iOS/intf.scm b/examples/iOS/intf.scm new file mode 100644 index 000000000..7cc0e54e0 --- /dev/null +++ b/examples/iOS/intf.scm @@ -0,0 +1,681 @@ +;;;============================================================================ + +;;; File: "intf.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("intf#")) + +(##include "~~lib/gambit#.scm") +(##include "~~lib/_gambit#.scm") + +(##include "intf#.scm") +(##include "url#.scm") + +(declare + (standard-bindings) + (extended-bindings) + (block) + (fixnum) + ;;(not safe) +) + + +;;;============================================================================ + +;; Interface with Objective-C. + +(c-declare #< + +const char *class_getName(Class cls); +id objc_getClass(const char *name); +id objc_msgSend(id self, SEL op, ...); + +id retain_id(id x) +{ + if (x != nil) + [x retain]; + return x; +} + +___SCMOBJ release_id(void *ptr) +{ + id x = ___CAST(id,ptr); + if (x != nil) + [x release]; + return ___FIX(___NO_ERR); +} + +Class retain_Class(Class x) +{ + if (x != nil) + [x retain]; + return x; +} + +___SCMOBJ release_Class(void *ptr) +{ + Class x = ___CAST(Class,ptr); + if (x != nil) + [x release]; + return ___FIX(___NO_ERR); +} + +c-declare-end +) + +(c-define-type id (pointer (struct "objc_object") (id Class) "release_id")) +(c-define-type Class (pointer (struct "objc_class") (Class id) "release_Class")) +(c-define-type SEL (pointer (struct "objc_selector") (SEL))) + +(define string->Class + (c-lambda (nonnull-char-string) Class + "___result = retain_Class(objc_getClass(___arg1));")) + +(define Class->string + (c-lambda (Class) nonnull-char-string + "___result = ___CAST(char*,class_getName(___arg1));")) ;;;TODO: remove cast + +(define string->SEL + (c-lambda (nonnull-UTF-8-string) SEL + "___result = sel_registerName(___arg1);")) + +(define SEL->string + (c-lambda (SEL) nonnull-UTF-8-string + "___result = ___CAST(char*,sel_getName(___arg1));")) ;;;TODO: remove cast + +;; Message sending (with 0, 1 and 2 parameters). + +(define send0 + (c-lambda (id SEL) id + "___result = retain_id(___CAST(id (*)(id, SEL),objc_msgSend)(___arg1, ___arg2));")) + +(define send1 + (c-lambda (id SEL id) id + "___result = retain_id(___CAST(id (*)(id, SEL, id),objc_msgSend)(___arg1, ___arg2, ___arg3));")) + +(define send2 + (c-lambda (id SEL id id) id + "___result = retain_id(___CAST(id (*)(id, SEL, id, id),objc_msgSend)(___arg1, ___arg2, ___arg3, ___arg4));")) + +;; Type conversions. + +(define id->string + (c-lambda (id) nonnull-UTF-8-string + "___result = ___CAST(char*,[___CAST(NSString*,___arg1) UTF8String]);")) ;;;TODO: remove cast + +(define string->id + (c-lambda (nonnull-UTF-8-string) id + "___result = retain_id([NSString stringWithUTF8String: ___arg1]);")) + +(define id->bool + (c-lambda (id) bool + "___result = [___CAST(NSNumber*,___arg1) boolValue];")) + +(define bool->id + (c-lambda (bool) id + "___result = retain_id([NSNumber numberWithBool:___arg1]);")) + +(define id->int + (c-lambda (id) int + "___result = [___CAST(NSNumber*,___arg1) intValue];")) + +(define int->id + (c-lambda (int) id + "___result = retain_id([NSNumber numberWithInt:___arg1]);")) + +(define id->float + (c-lambda (id) float + "___result = [___CAST(NSNumber*,___arg1) floatValue];")) + +(define float->id + (c-lambda (float) id + "___result = retain_id([NSNumber numberWithFloat:___arg1]);")) + +(define id->double + (c-lambda (id) double + "___result = [___CAST(NSNumber*,___arg1) doubleValue];")) + +(define double->id + (c-lambda (double) id + "___result = retain_id([NSNumber numberWithDouble:___arg1]);")) + +;;;---------------------------------------------------------------------------- + +;; Implement conversions between NSString* and Scheme strings. + +(c-declare #< + +___SCMOBJ SCMOBJ_to_NSStringSTAR(___SCMOBJ src, NSString **dst, int arg_num) +{ + /* + * Convert a Scheme string to NSString* . + */ + + NSString *result; + ___SCMOBJ ___temp; + + if (src == ___FAL) + result = nil; + else if (!___STRINGP(src)) + return ___FIX(___STOC_WCHARSTRING_ERR+arg_num); + else + { + int i; + int len = ___INT(___STRINGLENGTH(src)); + unichar *buf = ___alloc_mem(sizeof(unichar)*len); + + if (buf == 0) + return ___FIX(___STOC_HEAP_OVERFLOW_ERR+arg_num); + + for (i=0; iClass "NSDate")) +(define alloc (string->SEL "alloc")) +(define init (string->SEL "init")) +(define description (string->SEL "description")) + +(define (date) + (id->string + (send0 (send0 (send0 NSDate alloc) init) description))) + +;;;---------------------------------------------------------------------------- + +;; Interface with NSBundle Class. + +(define NSBundle (string->Class "NSBundle")) +(define mainBundle (string->SEL "mainBundle")) +(define objectForInfoDictionaryKey (string->SEL "objectForInfoDictionaryKey:")) + +(define (mainBundle-info key) + (let ((info + (send1 (send0 NSBundle mainBundle) + objectForInfoDictionaryKey (string->id key)))) + (and info + (id->string info)))) + +(define CFBundleName (mainBundle-info "CFBundleName")) +(define CFBundleDisplayName (mainBundle-info "CFBundleDisplayName")) + +;;;---------------------------------------------------------------------------- + +;; Interface with UIDevice Class. + +(define currentDevice-batteryLevel + (c-lambda () float + "___result = [[UIDevice currentDevice] batteryLevel];")) + +(define currentDevice-batteryMonitoringEnabled + (c-lambda () bool + "___result = [UIDevice currentDevice].batteryMonitoringEnabled;")) + +(define currentDevice-batteryMonitoringEnabled-set! + (c-lambda (bool) void + "[UIDevice currentDevice].batteryMonitoringEnabled = ___arg1;")) + +(define currentDevice-multitaskingSupported + (c-lambda () bool + "___result = [UIDevice currentDevice].multitaskingSupported;")) + +(define currentDevice-model + (c-lambda () NSString* + "___result = [[UIDevice currentDevice] model];")) + +(define currentDevice-name + (c-lambda () NSString* + "___result = [[UIDevice currentDevice] name];")) + +(define currentDevice-systemName + (c-lambda () NSString* + "___result = [[UIDevice currentDevice] systemName];")) + +(define currentDevice-systemVersion + (c-lambda () NSString* + "___result = [[UIDevice currentDevice] systemVersion];")) + +(define currentDevice-uniqueIdentifier + (c-lambda () NSString* + "___result = [[UIDevice currentDevice] uniqueIdentifier];")) + +(define (device-status) + (currentDevice-batteryMonitoringEnabled-set! #t) + (list (currentDevice-batteryLevel) + (currentDevice-batteryMonitoringEnabled) + (currentDevice-multitaskingSupported) + (currentDevice-model) + (currentDevice-name) + (currentDevice-systemName) + (currentDevice-systemVersion) + (currentDevice-uniqueIdentifier))) + +(define (device-model) + (let ((m (currentDevice-model))) + (cond ((has-prefix? m "iPhone") + 'iPhone) + ((has-prefix? m "iPod touch") + 'iPod-touch) + ((has-prefix? m "iPad") + 'iPad) + (else + #f)))) + +(define (UDID) + (currentDevice-uniqueIdentifier)) + + +;;;---------------------------------------------------------------------------- + +;; Interface with AudioToolbox. + +(c-declare #< + +c-declare-end +) + +(c-define-type SystemSoundID unsigned-int32) + +(define AudioServicesPlayAlertSound + (c-lambda (SystemSoundID) void "AudioServicesPlayAlertSound")) + +(define AudioServicesPlaySystemSound + (c-lambda (SystemSoundID) void "AudioServicesPlaySystemSound")) + +(define kSystemSoundID_FlashScreen #x00000FFE) +(define kSystemSoundID_Vibrate #x00000FFF) +(define kSystemSoundID_UserPreferredAlert #x00001000) + +;;;---------------------------------------------------------------------------- + +;; Interface with ViewController. + +(c-declare #<= len-str len-prefix) + (string=? (substring str 0 len-prefix) prefix) + (substring str len-prefix len-str))))) + +(define (get-event-parameters rest) + (call-with-input-string + rest + (lambda (port) + (map url-decode + (read-all port (lambda (p) (read-line p #\:))))))) + + +;;;---------------------------------------------------------------------------- + +;; Make it impossible to quit the application with a call to "exit" or +;; with a ",q" from the REPL. This is needed to conform to the iOS +;; Developer Program License Agreement (I don't know which section +;; but I remember it had to do with the iOS human interface design). + +(set! ##exit + (lambda (#!optional (status 0)) + (error "To exit, press the sleep button for 5 seconds then the home button for 10 seconds"))) + + +;;;---------------------------------------------------------------------------- + +;; Make it impossible to access files outside of Gambit REPL. This is +;; needed to conform to the iOS Developer Program License Agreement: +;; +;; 3.3.4 An Application may only read data from or write data to an +;; Application's designated container area on the device, except as +;; otherwise specified by Apple. + +;; The "~~" path will be equal to the app's bundle directory. The app's +;; home directory is the directory containing the app's bundle directory. + +(define app-home-dir + (##path-normalize "~~/..")) + +(define (contained-path-resolve path) + (let loop () + (let ((str (##path-expand path))) + (if (has-prefix? (##path-normalize str) app-home-dir) + str ;; only allow files in app directory + (begin + (error "App container violation") + (loop)))))) + +(set! ##path-resolve-hook contained-path-resolve) + +;; Make the current-directory and the "~" path equal to the app's +;; Documents directory. This directory is backed-up by iTunes. + +(set! ##os-path-homedir + (c-lambda () NSString* "get_documents_dir")) + +(current-directory "~") + + +;;;============================================================================ diff --git a/examples/iOS/makefile.in b/examples/iOS/makefile.in index 6e366f204..12241ac04 100644 --- a/examples/iOS/makefile.in +++ b/examples/iOS/makefile.in @@ -66,7 +66,9 @@ mandir = @mandir@ RCFILES = makefile.in README build-gambit-iOS GambitREPL.xcodeproj.tgz \ json.scm "json\#.scm" url.scm "url\#.scm" html.scm "html\#.scm" \ -wiki.scm "wiki\#.scm" program.scm program.h \ +wiki.scm "wiki\#.scm" repl-server.scm "repl-server\#.scm" \ +intf.scm "intf\#.scm" intf.h script.scm "script\#.scm" \ +repo.scm "repo\#.scm" help.scm "help\#.scm" program.scm \ Prefix.pch main.m \ AppDelegate.m AppDelegate.h ViewController.m ViewController.h \ AccessoryView.xib MainWindow.xib ViewController.xib \ @@ -76,6 +78,7 @@ Icon-unscaled-alpha.tiff \ 8ball.png edit.png f1.png f10.png f11.png f12.png f2.png f3.png \ f4.png f5.png f6.png f7.png f8.png f9.png heart.png note.png rocket.png \ stop.png user.png \ +button-abc.png button-cancel.png button-compass.png button-empty.png button-left-left.png button-left.png button-question.png button-right-right.png button-right.png button-up.png button-up-arrow.png \ key-8ball-46x42.png key-comma-46x42.png key-doublequote-46x42.png \ key-edit-46x42.png key-empty-46x42.png key-f1-46x42.png \ key-f10-46x42.png key-f11-46x42.png key-f12-46x42.png key-f2-46x42.png \ @@ -86,7 +89,8 @@ key-note-46x42.png key-plus-46x42.png key-quote-46x42.png \ key-rocket-46x42.png key-rparen-46x42.png key-sharp-46x42.png \ key-star-46x42.png key-stop-46x42.png key-user-46x42.png \ make-appstore-screenshots make-keys make-scaled-icons \ -Info.plist +Info.plist \ +help.html r5rs.html r5rs.pdf gambit-c.html GENDISTFILES = @@ -100,29 +104,40 @@ all-post: examples: prepare-for-xcode -prepare-for-xcode: json.m url.m html.m wiki.m program.m program_.m GambitREPL.xcodeproj +gambit-iOS: + @echo "*************************************************************" + @echo "* *" + @echo "* Building Gambit for iOS *" + @echo "* *" + @echo "* This builds the Gambit runtime library for *" + @echo "* the iPhone/iPad/iPod Touch devices and simulators *" + @echo "* *" + @echo "*************************************************************" chmod +x build-gambit-iOS + ./build-gambit-iOS + rm -rf lib + mkdir lib + cp gambit-iOS/current/lib/*.scm lib + cp gambit-iOS/current/doc/gambit-c.pdf . + +prepare-for-xcode: json.m url.m html.m wiki.m repl-server.m intf.m script.m repo.m help.m program.m program_.m GambitREPL.xcodeproj gambit-iOS @echo "*************************************************************" @echo "* *" @echo "* To complete the iOS example the following steps must be *" @echo "* completed manually: *" @echo "* *" - @echo "* 1) at the shell execute: ./build-gambit-iOS *" - @echo "* => this builds the Gambit runtime library for *" - @echo "* the iPhone/iPad/iPod Touch devices and simulators *" - @echo "* *" - @echo "* 2) open GambitREPL.xcodeproj in XCode 4.0 (or later) *" + @echo "* 1) open GambitREPL.xcodeproj in XCode 4.0 (or later) *" @echo "* *" - @echo "* 3) select the appropriate target (simulator or device) *" + @echo "* 2) select the appropriate target (simulator or device) *" @echo "* *" - @echo "* 4) select menu Product -> Run *" + @echo "* 3) select menu Product -> Run *" @echo "* *" @echo "*************************************************************" .scm.m: @SETDLPATH@ $(rootfromhere)/gsc/gsc -:~~bin=$(srcdirpfx)$(rootfromhere)/bin,~~lib=$(srcdirpfx)$(rootfromhere)/lib,~~include=$(srcdirpfx)$(rootfromhere)/include -f -c -check -o $*.m $(srcdirpfx)$*.scm -program_.m: json.m url.m html.m wiki.m program.m +program_.m: json.m url.m html.m wiki.m repl-server.m intf.m script.m repo.m help.m program.m @SETDLPATH@ $(rootfromhere)/gsc/gsc -:~~bin=$(srcdirpfx)$(rootfromhere)/bin,~~lib=$(srcdirpfx)$(rootfromhere)/lib,~~include=$(srcdirpfx)$(rootfromhere)/include -f -link -o $@ $^ GambitREPL.xcodeproj: GambitREPL.xcodeproj.tgz @@ -145,7 +160,7 @@ uninstall-post: mostlyclean-pre: mostlyclean-post: - rm -f json.m url.m html.m wiki.m program.m program_.m + rm -f json.m url.m html.m wiki.m repl-server.m intf.m script.m repo.m help.m program.m program_.m clean-pre: mostlyclean-pre diff --git a/examples/iOS/program.h b/examples/iOS/program.h deleted file mode 100644 index a93910f9f..000000000 --- a/examples/iOS/program.h +++ /dev/null @@ -1,16 +0,0 @@ -/* File: "program.h" */ - -/* - * Scheme functions which can be called from C. These functions are - * declared with a c-define in "program.scm". - */ - -extern NSString *eval_string(NSString *); - -extern double send_input(NSString *); - -extern double send_event(NSString *); - -extern double send_key(NSString *); - -extern double heartbeat(); diff --git a/examples/iOS/program.scm b/examples/iOS/program.scm index bef41017b..64b218fdd 100644 --- a/examples/iOS/program.scm +++ b/examples/iOS/program.scm @@ -6,8 +6,7 @@ ;; This program implements the "Gambit REPL" application for iOS ;; devices. It is a simple development environment for Scheme. The -;; user can interact with a REPL, edit small scripts, run them and -;; share them on a public script repository. +;; user can interact with a REPL, and edit small scripts. ;;;============================================================================ @@ -16,69 +15,31 @@ (##include "~~lib/gambit#.scm") (##include "~~lib/_gambit#.scm") +(##namespace ("gr#" help)) ;; don't import help + (##include "wiki#.scm") (##include "html#.scm") (##include "url#.scm") (##include "json#.scm") +(##include "repl-server#.scm") +(##include "intf#.scm") +(##include "script#.scm") +(##include "repo#.scm") +(##include "help#.scm") (##namespace ("" splash repl repl-eval + repl-server + wiki + help edit - login - repo reset-scripts - upload-script - download-script - delete-script + remove-script + store-script + fetch-script view-script - obtain-script - start-repl-server - show-textView - show-webView - set-textView-font - set-textView-content - get-textView-content - add-output-to-textView - add-input-to-textView - set-webView-content - open-URL - set-pref - get-pref - set-page - set-page-content - has-prefix? - get-event-parameters - - string->Class - Class->string - string->SEL - SEL->string - send0 - send1 - send2 - id->string - string->id - id->bool - bool->id - id->int - int->id - id->float - float->id - id->double - double->id - - date - - device-status - UDID - - AudioServicesPlayAlertSound - AudioServicesPlaySystemSound - kSystemSoundID_FlashScreen - kSystemSoundID_Vibrate - kSystemSoundID_UserPreferredAlert )) (declare @@ -91,733 +52,47 @@ ;;;---------------------------------------------------------------------------- -;; Make it impossible to access files outside of Gambit REPL. This is -;; needed to respect clause 2.6 of the App Store Review Guidelines: -;; "Apps that read or write data outside its designated container area -;; will be rejected". - -(define (contained-path-resolve path) - (let loop () - (let ((str (##path-expand path))) - (if (has-prefix? (##path-normalize str) app-dir) - str ;; only allow files in app directory - (begin - (error "App container violation") - (loop)))))) - -(set! ##path-resolve-hook contained-path-resolve) - -;; Make the current-directory and the "~~" path equal to the program's -;; .app directory. +;; Add cond-expand features to identify Gambit-REPL. -(define app-dir - (##path-normalize (path-directory (car (command-line))))) - -(set! ##os-path-gambcdir - (lambda () app-dir)) - -(current-directory app-dir) +(set! ##cond-expand-features + (cons 'Gambit-REPL + (cons 'Gambit-REPL-iOS + (cons 'Gambit-REPL-v4.0 + ##cond-expand-features)))) ;;;---------------------------------------------------------------------------- -;; Interface with Objective-C. - -(c-declare #< - -const char *class_getName(Class cls); -id objc_getClass(const char *name); -id objc_msgSend(id self, SEL op, ...); - -id retain_id(id x) -{ - if (x != nil) - [x retain]; - return x; -} - -___SCMOBJ release_id(void *ptr) -{ - id x = ___CAST(id,ptr); - if (x != nil) - [x release]; - return ___FIX(___NO_ERR); -} - -Class retain_Class(Class x) -{ - if (x != nil) - [x retain]; - return x; -} - -___SCMOBJ release_Class(void *ptr) -{ - Class x = ___CAST(Class,ptr); - if (x != nil) - [x release]; - return ___FIX(___NO_ERR); -} - -c-declare-end -) - -(c-define-type id (pointer (struct "objc_object") (id Class) "release_id")) -(c-define-type Class (pointer (struct "objc_class") (Class id) "release_Class")) -(c-define-type SEL (pointer (struct "objc_selector") (SEL))) - -(define string->Class - (c-lambda (nonnull-char-string) Class - "___result = retain_Class(objc_getClass(___arg1));")) - -(define Class->string - (c-lambda (Class) nonnull-char-string - "___result = ___CAST(char*,class_getName(___arg1));")) ;;;TODO: remove cast - -(define string->SEL - (c-lambda (nonnull-UTF-8-string) SEL - "___result = sel_registerName(___arg1);")) - -(define SEL->string - (c-lambda (SEL) nonnull-UTF-8-string - "___result = ___CAST(char*,sel_getName(___arg1));")) ;;;TODO: remove cast - -;; Message sending (with 0, 1 and 2 parameters). - -(define send0 - (c-lambda (id SEL) id - "___result = retain_id(___CAST(id (*)(id, SEL),objc_msgSend)(___arg1, ___arg2));")) - -(define send1 - (c-lambda (id SEL id) id - "___result = retain_id(___CAST(id (*)(id, SEL, id),objc_msgSend)(___arg1, ___arg2, ___arg3));")) - -(define send2 - (c-lambda (id SEL id id) id - "___result = retain_id(___CAST(id (*)(id, SEL, id, id),objc_msgSend)(___arg1, ___arg2, ___arg3, ___arg4));")) - -;; Type conversions. - -(define id->string - (c-lambda (id) nonnull-UTF-8-string - "___result = ___CAST(char*,[___CAST(NSString*,___arg1) UTF8String]);")) ;;;TODO: remove cast - -(define string->id - (c-lambda (nonnull-UTF-8-string) id - "___result = retain_id([NSString stringWithUTF8String: ___arg1]);")) - -(define id->bool - (c-lambda (id) bool - "___result = [___CAST(NSNumber*,___arg1) boolValue];")) - -(define bool->id - (c-lambda (bool) id - "___result = retain_id([NSNumber numberWithBool:___arg1]);")) - -(define id->int - (c-lambda (id) int - "___result = [___CAST(NSNumber*,___arg1) intValue];")) - -(define int->id - (c-lambda (int) id - "___result = retain_id([NSNumber numberWithInt:___arg1]);")) - -(define id->float - (c-lambda (id) float - "___result = [___CAST(NSNumber*,___arg1) floatValue];")) - -(define float->id - (c-lambda (float) id - "___result = retain_id([NSNumber numberWithFloat:___arg1]);")) - -(define id->double - (c-lambda (id) double - "___result = [___CAST(NSNumber*,___arg1) doubleValue];")) - -(define double->id - (c-lambda (double) id - "___result = retain_id([NSNumber numberWithDouble:___arg1]);")) - -;;;---------------------------------------------------------------------------- - -;; Implement conversions between NSString* and Scheme strings. - -(c-declare #< - -___SCMOBJ SCMOBJ_to_NSStringSTAR(___SCMOBJ src, NSString **dst, int arg_num) -{ - /* - * Convert a Scheme string to NSString* . - */ - - NSString *result; - ___SCMOBJ ___temp; - - if (src == ___FAL) - result = nil; - else if (!___STRINGP(src)) - return ___FIX(___STOC_WCHARSTRING_ERR+arg_num); - else - { - int i; - int len = ___INT(___STRINGLENGTH(src)); - unichar *buf = ___alloc_mem(sizeof(unichar)*len); - - if (buf == 0) - return ___FIX(___STOC_HEAP_OVERFLOW_ERR+arg_num); - - for (i=0; i + - result = ___alloc_scmobj(___sSTRING, len<<___LCS, ___STILL); + - if (___FIXNUMP(result)) - return ___FIX(___CTOS_HEAP_OVERFLOW_ERR+arg_num); + - - - common-html-header-end @@ -993,13 +271,14 @@ common-html-header-end (define splash-page-content-part1 #< +

Welcome to splash-page-content-part1-end ) (define splash-page-content-part2 #<, a Scheme development environment built with the Gambit Scheme programming system. +, a Scheme development environment based on the Gambit Scheme programming system.

    @@ -1009,11 +288,10 @@ splash-page-content-part1-end

-After the ">" prompt enter your command then RETURN and the REPL will display the result. Here is a sample interaction: -

- +In the REPL view, enter your command after the > prompt, then tap return to display the result. Here is a sample interaction:
+
> (+ 1 (/ (* 2 2) (sqrt 9)))
7/3
> (expt 2 100)
@@ -1024,275 +302,120 @@ After the ">" prompt enter your command then RE 1
4
9
-> (exit)
+

-
- -
Edit Scripts
-
Start Server
-
Start REPL
- -
splash-page-content-part2-end ) -(define (splash) - (set-page +(define (set-splash-view) + (set-view-content + 0 (list common-html-header splash-page-content-part1 CFBundleDisplayName splash-page-content-part2) - (lambda (event) - (cond ((equal? event "event:repl") - (repl)) - - ((equal? event "event:edit") - (edit)) - - ((equal? event "event:server") - (repl) - (start-repl-server)) - - ((equal? event "event:wiki") - (repl) - (open-URL - (string-append - "http://" - wiki-server-address - wiki-root - "/index.php"))))) #t)) -(define (repl) - (show-textView)) - -(define (repl-eval str) - (if (string? str) - (begin - (add-output-to-textView str) - (send-input str) - (repl)))) - -(set! ##primordial-exception-handler-hook - (lambda (exc other-handler) - (repl) ;; switch to REPL view on errors - (##repl-exception-handler-hook exc other-handler))) - -(define (load-script name script) - (let ((port (open-input-string script))) - - (if (not (equal? name "")) - ;; Hack... set the names of the port to match the name - (##vector-set! port 4 (lambda (port) name))) +(define (splash) + (set-navigation -1) + (set-event-handler + (lambda (old-event-handler) + generic-event-handler)) + (show-view 0)) - (let ((x - (##read-all-as-a-begin-expr-from-port - port - (##current-readtable) - ##wrap-datum - ##unwrap-datum - #f ;; Scheme syntax - #t))) - (if (not (##fixnum? x)) - (##eval-module (##vector-ref x 1) ##interaction-cte))))) ;;;---------------------------------------------------------------------------- -;; Script editing. +;; Help page. -(define predefined-scripts '( +(define current-help-document #f) -("hello" . -#<Hello! -END -) -(thread-sleep! 5) ;; wait 5 seconds -(edit) ;; return to this page -EOF -) +(define (show-help-document docu anchor) + (let ((load-docu? (not (equal? docu current-help-document)))) -("fact100" . -#<\n" - (with-output-to-string - "" - (lambda () - (pretty-print - (device-status)))) - "\n")) -(show-webView) - -(thread-sleep! 5) ;; wait 5 seconds -(edit) ;; return to this page -EOF -) + (set-event-handler + (lambda (old-event-handler) + (lambda (event) + (cond ((and load-docu? (equal? event "event:loaded")) + (if (not (equal? docu main-help-document)) + (show-cancelButton)) + (goto-anchor)) -("F12" . -#< -var nb_scripts = edit-page-content-part1-end ) (define edit-page-content-part2 #<:..."); - return false; +function click_delete(index) +{ if (confirm('Are you sure you want to delete this script from the Edit view?')) + send_event_with_scripts("delete",index); } +function lose_focus() +{ return event_with_scripts("exit",0); } + -
-
Script Repo
-
New Script
-
Show REPL
-
+ +
+
+
-edit-page-content-part2-end +edit-page-content-part4-end ) -(define edit-page-content-part3 #< -edit-page-content-part3-end +edit-page-content-part5-end ) +(define edit-page-script-rows-iPad 20) +(define edit-page-script-rows-default 10) + +(define edit-page-script-rows + (case (device-model) + ((iPad) edit-page-script-rows-iPad) + (else edit-page-script-rows-default))) + (define (html-for-local-scripts scripts) (define (html script name index) (list "
\n" - "\n" - "
" "
\n" "
Run
\n" "       " - "
Share
\n" + "
Save
\n" "       " "
Delete
\n" "
\n")) @@ -1402,73 +542,211 @@ edit-page-content-part3-end (let* ((x (car scripts)) (name (car x)) (script (cdr x))) - (loop (cdr scripts) (+ i 1) (cons (html script name i) accum))) + (loop (cdr scripts) + (+ i 1) + (cons (html (add-script-name-if-needed name script) name i) + accum))) (reverse accum)))) -(define (edit) - - (define (get-index-and-update-script-db rest) - (let ((x (get-event-parameters rest))) - (if (pair? x) - (let ((index (string->number (car x)))) - (let loop ((lst (cdr x)) (rev-scripts '())) - (if (and (pair? lst) - (pair? (cdr lst))) - (let ((name (car lst)) - (script (cadr lst))) - (loop (cddr lst) - (cons (cons name script) rev-scripts))) - (let ((new-script-db (reverse rev-scripts))) - - (set-pref "run-main-script" "yes") - - (set! script-db new-script-db) - (save-script-db) - index)))) - #f))) - - (set-page +(define (add-script-name-if-needed name script) + (if (not (wiki-script-name-type name)) + script + (let ((name-in-script (extract-script-name script))) + (if (equal? name name-in-script) + script + (string-append + script-name-prefix + name + "\n\n" + script))))) + +(define (set-edit-view) + (set-view-content + 3 (let ((scripts (get-script-db))) (list common-html-header edit-page-content-part1 - (length scripts) + "var nb_scripts = " (length scripts) ";\n" edit-page-content-part2 + (if repo-enabled? + edit-page-content-part3 + "") + edit-page-content-part4 (html-for-local-scripts scripts) - edit-page-content-part3)) - (lambda (event) - (cond ((has-prefix? event "event:run:") => - (lambda (rest) - (run-script-event - (get-index-and-update-script-db rest)))) - - ((has-prefix? event "event:share:") => - (lambda (rest) - (share-script-event - (get-index-and-update-script-db rest)))) - - ((has-prefix? event "event:delete:") => - (lambda (rest) - (delete-script-event - (get-index-and-update-script-db rest)) - (edit))) - - ((has-prefix? event "event:repo:") => - (lambda (rest) - (get-index-and-update-script-db rest) - (repo edit))) - - ((has-prefix? event "event:repl:") => - (lambda (rest) - (get-index-and-update-script-db rest) - (repl))) - - ((has-prefix? event "event:new:") => - (lambda (rest) - (get-index-and-update-script-db rest) - (new-script) - (edit))))) + edit-page-content-part5)) #t)) +(define (edit) + (set-navigation 3) + (set-event-handler + (lambda (old-event-handler) + (lambda (event) + (handle-edit-event + event + (lambda () + (handle-navigation-event + event + (lambda () + (let ((new-event (eval-js-in-webView 3 "lose_focus()"))) + (and (string? new-event) + (handle-edit-event + new-event + (lambda () + #f))))))))))) + (show-view 3)) + +(define (get-index-and-update-script-db rest) + (let ((x (get-event-parameters rest))) + (if (pair? x) + (let ((index (string->number (car x)))) + (let loop ((lst (cdr x)) (rev-scripts '())) + (if (pair? lst) + (let ((script (car lst))) + (loop (cdr lst) + (cons (cons (extract-script-name script) script) + rev-scripts))) + (let ((new-script-db (reverse rev-scripts))) + + (set-pref "run-main-script" "yes") + + (set! script-db new-script-db) + (save-script-db) + index)))) + #f))) + +(define (handle-edit-event event otherwise) + (cond ((has-prefix? event "event:new:") => + (lambda (rest) + (get-index-and-update-script-db rest) + (new-script) + (set-edit-view))) + + ((has-prefix? event "event:run:") => + (lambda (rest) + (run-script-event + (get-index-and-update-script-db rest)))) + + ((has-prefix? event "event:save:") => + (lambda (rest) + (save-script-event + (get-index-and-update-script-db rest)))) + + ((has-prefix? event "event:remove:") => + (lambda (rest) + (remove-script-event + (get-index-and-update-script-db rest)))) + + ((has-prefix? event "event:delete:") => + (lambda (rest) + (delete-script-event + (get-index-and-update-script-db rest)) + (set-edit-view))) + + ((has-prefix? event "event:exit:") => + (lambda (rest) + (get-index-and-update-script-db rest))) + + (else + (otherwise)))) + +(define (handle-navigation-event event lose-focus-handler) + (let ((nav (has-prefix? event "NAV"))) + (if nav + (let ((n (string->number nav))) + (lose-focus-handler) + (case n + ((1) + (wiki)) + + ((2) + (help)) + + ((3) + (edit)) + + (else + (repl))))))) + +(define (wiki-event-handler event) + (or (and (equal? event "event:wiki") + (begin + (visit-wiki) + #t)) + (and (equal? event "event:wiki-Gambit-REPL") + (begin + (visit-wiki-Gambit-REPL) + #t)))) + +(define (visit-wiki) + (open-URL + (string-append + "http://" + wiki-server-address + wiki-root + "/index.php"))) + +(define (visit-wiki-Gambit-REPL) + (open-URL + (string-append + "http://" + wiki-server-address + wiki-root + "/index.php/Gambit_REPL"))) + +(define latest-pasteboard #f) + +(define (handle-app-become-active-event event) + (and (equal? event "app-become-active") + (let* ((script (get-pasteboard)) + (name (and script + (not (equal? script latest-pasteboard)) + (extract-script-name script)))) + (set! latest-pasteboard script) + (if name + (set-event-handler + (lambda (old-event-handler) + (popup-alert (string-append CFBundleName ".app") + (string-append + "Create the script\n\n" + name + "\n\nin the Edit view from the content of the pasteboard?") + "No" + "Yes") + (lambda (event) + + (define (done accept?) + (set-event-handler + (lambda (new-event-handler) + old-event-handler)) + (if accept? + (begin + (add-script name script) + (set-edit-view) + (edit)))) + + (cond ((equal? event "popup-alert-cancel") + (done #f)) + ((equal? event "popup-alert-accept") + (done #t))))))) + #t))) + +(define (handle-create-account-event event) + (and (equal? event "event:create-account") + (begin + (open-URL + (string-append + "http://" + wiki-server-address + wiki-root + "/index.php/Special:RequestAccount")) + #t))) + +(define (generic-event-handler event) + (or (wiki-event-handler event) + (handle-app-become-active-event event) + (handle-create-account-event event) + (handle-navigation-event event (lambda () #f)))) + (define run-script-event #f) (set! run-script-event (lambda (index) @@ -1478,64 +756,108 @@ edit-page-content-part3-end (script (cdr name-script))) (run-script name script)))))) -(define (run-script name script) - (##thread-interrupt! - (macro-primordial-thread) - (lambda () - (##repl-channel-release-ownership!) ;; to prevent deadlock... - (with-exception-handler - ##primordial-exception-handler - (lambda () - (load-script name script))) - (##void)))) +(define save-script-event #f) +(set! save-script-event + (lambda (index) + (let ((name-script (get-script-at-index index))) + (and name-script + (let ((name (car name-script)) + (script (cdr name-script))) + (store-script name script edit)))))) -(define share-script-event #f) -(set! share-script-event +(define remove-script-event #f) +(set! remove-script-event (lambda (index) (let ((name-script (get-script-at-index index))) (and name-script (let ((name (car name-script)) (script (cdr name-script))) - (if (equal? script "") - (delete-script name edit) - (upload-script name script edit))))))) - -(define (upload-script name script #!optional (back repl)) - (repo-transaction - (lambda () - (wiki-script-name-verify name) - (wiki-script-store name script) - (back)) - "" - (list "

Uploading script

" (html-escape name) "
") - "The script has been uploaded to the repository" - "Upload failed!" - back)) + (remove-script name edit)))))) -(define (download-script name #!optional (back repl)) - (repo-transaction - (lambda () - (wiki-script-name-verify name) - (let ((script (wiki-script-fetch name))) - (add-script name script) - (back))) - "" - (list "

Downloading script

" (html-escape name) "
") - "The script has been downloaded from the repository" - "Download failed!" - back)) +(define (reset-scripts) + (script#reset-scripts) + (set-edit-view)) -(define (delete-script name #!optional (back repl)) - (repo-transaction - (lambda () - (wiki-script-name-verify name) - (wiki-script-delete name) - (back)) - "" - (list "

Deleting script

" (html-escape name) "
") - "The script has been deleted from the repository" - "Delete failed!" - back)) +(define (remove-script name #!optional (back repl)) + (case (wiki-script-name-type name) + ((wiki) + (repo-transaction + (lambda () + (wiki-script-name-verify name) + (wiki-script-remove name) + (back)) + "" + (list "

Removing script

" (html-escape name) "
") + "The script has been removed from the Gambit wiki" + "Could not remove script!" + back)) + + ((file) + (with-exception-catcher + (lambda (e) + (display-exception e (repl-output-port)) + (repl)) + (lambda () + (delete-file (##path-expand name "~")))) + (back)))) + +(define (store-script name script #!optional (back repl)) + (case (wiki-script-name-type name) + ((wiki) + (repo-transaction + (lambda () + (wiki-script-name-verify name) + (wiki-script-store name script) + (back)) + "" + (list "

Storing script

" (html-escape name) "
") + "The script has been stored on the Gambit wiki" + "Could not store script!" + back)) + + ((file) + (with-exception-catcher + (lambda (e) + (display-exception e (repl-output-port)) + (repl)) + (lambda () + (call-with-output-file + (##path-expand name "~") + (lambda (port) + (display script port))))) + (back)))) + +(define (fetch-script name #!optional (back repl)) + (case (wiki-script-name-type name) + ((wiki) + (repo-transaction + (lambda () + (wiki-script-name-verify name) + (let ((script (wiki-script-fetch name))) + (add-script name script) + (set-edit-view) + (back))) + "" + (list "

Fetching script

" (html-escape name) "
") + "The script has been fetched from the Gambit wiki" + "Could not fetch script!" + back)) + + ((file) + (with-exception-catcher + (lambda (e) + (display-exception e (repl-output-port)) + (repl)) + (lambda () + (let ((script + (call-with-input-file + (##path-expand name "~") + (lambda (port) + (read-line port #f))))) + (add-script name script) + (set-edit-view) + (back)))) + (back)))) (define (delete-script-event index) (let loop ((scripts (get-script-db)) (i 0) (accum '())) @@ -1546,12 +868,22 @@ edit-page-content-part3-end (loop (cdr scripts) (+ i 1) (cons (car scripts) accum))))) (save-script-db)) -(define (new-script) - (add-script "untitled" "")) +(define script-name-prefix ";;; ") ;; must be consistent with the definition of the click_save JavaScript function + +(define (extract-script-name script) + (let* ((line1 (first-line script)) + (name (has-prefix? line1 script-name-prefix))) + (and (wiki-script-name-type name) + name))) + +(define (first-line str) + (let loop ((i 0)) + (if (< i (string-length str)) + (if (char=? (string-ref str i) #\newline) + (substring str 0 i) + (loop (+ i 1))) + str))) -(define (add-script name script) - (set! script-db (cons (cons name script) (get-script-db))) - (save-script-db)) ;;;---------------------------------------------------------------------------- @@ -1561,39 +893,44 @@ edit-page-content-part3-end - repo-page-content-part1-end ) (define repo-page-content-part2 #< -
Back
-
Edit Scripts
-
Show REPL
- - +
+
+
repo-page-content-part2-end ) (define repo-page-content-part3 #< +  + + +repo-page-content-part3-end +) + +(define repo-page-content-part4 #< -repo-page-content-part3-end +repo-page-content-part4-end ) -(define repo-page-content-part4 #< -repo-page-content-part4-end +repo-page-content-part5-end ) (define (html-for-script-tree tree) @@ -1606,7 +943,7 @@ repo-page-content-part4-end (list "\n" "\n") + "';\">▶\n") (list "\n" @@ -1624,19 +961,32 @@ repo-page-content-part4-end (loop (cdr tree) (cons (html branch) accum))) (reverse accum)))) -(define (repo #!optional (back repl)) - (auto-login - (lambda () - (repo-transaction - (lambda () - (let ((scripts (wiki-script-list))) - (repo-browse back (script-list->tree scripts)))) - repo-page-content-part2 - "" - #f - "Could not get list of scripts!" - back)) - back)) +(define repo-enabled? #f) + +(define (repo-enable!) + (if (not repo-enabled?) + (begin + (set! repo-enabled? #t) + (segm-ctrl-set-title 1 "Repo")))) + +(define (repo) + (repo-enable!) + (wiki)) + +(define (wiki) + (if (not repo-enabled?) + (begin + (visit-wiki-Gambit-REPL) + (repl)) + (repo-transaction + (lambda () + (let ((scripts (wiki-script-list))) + (repo-browse #f (script-list->tree scripts)))) + repo-page-content-part3 + (list "

Accessing Gambit wiki


") + #f + "Could not get list of scripts!" + repl))) (define (script-list->tree scripts) @@ -1672,42 +1022,46 @@ repo-page-content-part4-end (cvt scripts "")) (define (repo-browse back tree) - (set-page + (set-navigation 1) + (set-event-handler + (lambda (old-event-handler) + (lambda (event) + (cond ((has-prefix? event "event:view:") => + (lambda (rest) + (let* ((params (get-event-parameters rest)) + (name (car params)) + (branch (assoc name tree))) + (if branch + (let ((subtree (cdr branch))) + (if (pair? subtree) + (repo-browse (lambda () (repo-browse back tree)) + subtree) + (view-script name))))))) + + ((has-prefix? event "event:get:") => + (lambda (rest) + (let* ((params (get-event-parameters rest)) + (name (car params))) + (get-repo-script-event name edit)))) + + ((equal? event "event:back") + (back)) + + (else + (generic-event-handler event)))))) + (set-view-content + 1 (list common-html-header repo-page-content-part1 - repo-page-content-part2 - repo-page-content-part3 + (if back + repo-page-content-part2 + repo-page-content-part3) + repo-page-content-part4 (html-for-script-tree tree) - repo-page-content-part4) - (lambda (event) - (cond ((has-prefix? event "event:view:") => - (lambda (rest) - (let* ((params (get-event-parameters rest)) - (name (car params)) - (branch (assoc name tree))) - (if branch - (let ((subtree (cdr branch))) - (if (pair? subtree) - (repo-browse (lambda () (repo-browse back tree)) - subtree) - (view-script name))) - (back))))) ;; this should never happen - - ((has-prefix? event "event:get:") => - (lambda (rest) - (let* ((params (get-event-parameters rest)) - (name (car params))) - (get-repo-script-event name edit)))) - - ((equal? event "event:back") - (back)) - - ((equal? event "event:repl") - (repl)) - - ((equal? event "event:edit") - (edit)))) - #t)) + repo-page-content-part5) + + #t) + (show-view 1)) (define (view-script name) (open-URL @@ -1719,38 +1073,9 @@ repo-page-content-part4-end (url-encode (string-append wiki-script-prefix name))))) -(define obtain-script #f) -(set! obtain-script view-script) - (define get-repo-script-event #f) -(set! get-repo-script-event - (lambda (name #!optional (back repl)) - (let ((script - (string-append - obtain-script-prefix - name - obtain-script-suffix))) - (add-script name script) - (back)))) +(set! get-repo-script-event fetch-script) -(define obtain-script-prefix #< If you don't have an account, you should
-
Create an account

+
Create an account

It's free! @@ -1987,50 +1316,43 @@ login-page-content-part5-end (login-with-page (make-initial-login-page) success fail)) (define (login-with-page page success fail) - (set-page - page - (lambda (event) - (cond ((has-prefix? event "event:login:") => - (lambda (rest) - (let* ((params (get-event-parameters rest)) - (username (car params)) - (password (cadr params)) - (remember-pass? (equal? (caddr params) "on"))) - (attempt-login success - fail - username - password - remember-pass?)))) - - ((equal? event "event:cancel") - (fail)) - - ((equal? event "event:create") - (open-URL - (string-append - "http://" - wiki-server-address - wiki-root - "/index.php/Special:RequestAccount"))))) - #t)) + (set-navigation 1) + (set-event-handler + (lambda (old-event-handler) + (lambda (event) + (cond ((has-prefix? event "event:login:") => + (lambda (rest) + (let* ((params (get-event-parameters rest)) + (username (car params)) + (password (cadr params)) + (remember-pass? (equal? (caddr params) "on"))) + (attempt-login success + fail + username + password + remember-pass?)))) + + ((equal? event "event:cancel") + (fail)) + + (else + (generic-event-handler event)))))) + (set-view-content 1 page #t) + (show-view 1)) (define (attempt-login success fail username password remember-pass?) - (set! login-info - (list username - (if remember-pass? password "") - remember-pass?)) + (set-login-info username password remember-pass?) (save-login-info) - (set-page + (set-view-content + 1 (make-login-page username password remember-pass? spinner-html) - (lambda (event) - #f) #t) ((with-exception-catcher @@ -2055,20 +1377,48 @@ login-page-content-part5-end (wiki-logout) (wiki-login username password #t) - (set-page + (set-view-content + 1 (make-login-page username password remember-pass? "
You are now logged in!
") - (lambda (event) - #f) #t) (thread-sleep! 2) ;; display success message for 2 seconds success)))) + +;;;---------------------------------------------------------------------------- + +;; Opening URLs. + +(##namespace ("" open-URL)) + +(define (open-URL str) + (if (string? str) + (intf#open-URL str))) + + +;;;---------------------------------------------------------------------------- + +;; Key handler. + +(set! handle-key + (lambda (str) + (if (char=? #\F (string-ref str 0)) + (let ((script (get-script-by-name str))) + (cond (script + (run-script str script)) + ((equal? str "F12") + (##thread-interrupt! (macro-primordial-thread))) + (else + (add-input-to-textView 0 (string-append "<" str ">"))))) + (add-input-to-textView 0 str)))) + + ;;;---------------------------------------------------------------------------- ;; Start the main REPL in the primordial thread, and create a second @@ -2086,6 +1436,12 @@ login-page-content-part5-end ;; the primordial thread is running this... + (set-splash-view) ;; init the splash view + (set-edit-view) ;; init the edit view + + (if (equal? CFBundleDisplayName "Gambit REPL dev") + (repo-enable!)) + (if (get-pref "run-main-script") (begin @@ -2104,4 +1460,5 @@ login-page-content-part5-end (exit))) + ;;;============================================================================ diff --git a/examples/iOS/r5rs.html b/examples/iOS/r5rs.html new file mode 100644 index 000000000..53778196d --- /dev/null +++ b/examples/iOS/r5rs.html @@ -0,0 +1,9309 @@ + + + + + + + + + + + + + + + + + + + +
=>
Get
+ + + + + + + + + +
Back: Revised(5) Report on the Algorithmic Language SchemeForward: Introduction   FastBack: Revised(5) Report on the Algorithmic Language SchemeUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: IntroductionTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Revised(5) Report on the Algorithmic Language Scheme

+ +
+ +
[View PDF version]
+ +

RICHARD KELSEY, WILLIAM CLINGER, AND JONATHAN REES (Editors) +
+

+ + + + + +
H. ABELSONR. K. DYBVIGC. T. HAYNESG. J. ROZAS
N. I. ADAMS IVD. P. FRIEDMANE. KOHLBECKERG. L. STEELE JR.
D. H. BARTLEYR. HALSTEADD. OXLEYG. J. SUSSMAN
G. BROOKSC. HANSONK. M. PITMANM. WAND
+
+ +

Dedicated to the Memory of Robert Hieb +

+ + + +

Summary

+ + +

The report gives a defining description of the programming language +Scheme. Scheme is a statically scoped and properly tail-recursive +dialect of the Lisp programming language invented by Guy Lewis +Steele Jr. and Gerald Jay Sussman. It was designed to have an +exceptionally clear and simple semantics and few different ways to +form expressions. A wide variety of programming paradigms, including +imperative, functional, and message passing styles, find convenient +expression in Scheme. +

+

The introduction offers a brief history of the language and of +the report. +

+

The first three chapters present the fundamental ideas of the +language and describe the notational conventions used for describing the +language and for writing programs in the language. +

+

Chapters Expressions and Program structure describe +the syntax and semantics of expressions, programs, and definitions. +

+

Chapter Standard procedures describes Scheme's built-in +procedures, which include all of the language's data manipulation and +input/output primitives. +

+

Chapter Formal syntax and semantics provides a formal syntax for Scheme +written in extended BNF, along with a formal denotational semantics. +An example of the use of the language follows the formal syntax and +semantics. +

+

The report concludes with a list of references and an +alphabetic index. +

+ + + + + + + + +
+ + + + + + + + + + + +
Back: Revised(5) Report on the Algorithmic Language SchemeForward: Introduction   FastBack: Revised(5) Report on the Algorithmic Language SchemeUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: IntroductionTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+

Contents

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: ContentsForward: Background   FastBack: ContentsUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: 1. Overview of SchemeTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Introduction

+ + + + + + + + + +

Programming languages should be designed not by piling feature on top of +feature, but by removing the weaknesses and restrictions that make additional +features appear necessary. Scheme demonstrates that a very small number +of rules for forming expressions, with no restrictions on how they are +composed, suffice to form a practical and efficient programming language +that is flexible enough to support most of the major programming +paradigms in use today. +

+

Scheme +was one of the first programming languages to incorporate first class +procedures as in the lambda calculus, thereby proving the usefulness of +static scope rules and block structure in a dynamically typed language. +Scheme was the first major dialect of Lisp to distinguish procedures +from lambda expressions and symbols, to use a single lexical +environment for all variables, and to evaluate the operator position +of a procedure call in the same way as an operand position. By relying +entirely on procedure calls to express iteration, Scheme emphasized the +fact that tail-recursive procedure calls are essentially goto's that +pass arguments. Scheme was the first widely used programming language to +embrace first class escape procedures, from which all previously known +sequential control structures can be synthesized. A subsequent +version of Scheme introduced the concept of exact and inexact numbers, +an extension of Common Lisp's generic arithmetic. +More recently, Scheme became the first programming language to support +hygienic macros, which permit the syntax of a block-structured language +to be extended in a consistent and reliable manner. +

+ + +
+ + + + + + + + + + + +
Back: IntroductionForward: Acknowledgements   FastBack: IntroductionUp: IntroductionFastForward: 1. Overview of SchemeTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Background

+ + +

The first description of Scheme was written in +1975 [Scheme75]. A revised report [Scheme78] + appeared in 1978, which described the evolution +of the language as its MIT implementation was upgraded to support an +innovative compiler [Rabbit]. Three distinct projects began in +1981 and 1982 to use variants of Scheme for courses at MIT, Yale, and +Indiana University [Rees82], [MITScheme], [Scheme311]. An introductory +computer science textbook using Scheme was published in +1984 [SICP]. +

+

As Scheme became more widespread, +local dialects began to diverge until students and researchers +occasionally found it difficult to understand code written at other +sites. +Fifteen representatives of the major implementations of Scheme therefore +met in October 1984 to work toward a better and more widely accepted +standard for Scheme. +

+

Their report [RRRS] +was published at MIT and Indiana University in the summer of 1985. +Further revision took place in the spring of 1986 [R3RS], +and in the spring of 1988 [R4RS]. +The present report reflects further revisions agreed upon in a meeting +at Xerox PARC in June 1992. +

+ + + + +
+
+
+ +

We intend this report to belong to the entire Scheme community, and so +we grant permission to copy it in whole or in part without fee. In +particular, we encourage implementors of Scheme to use this report as +a starting point for manuals and other documentation, modifying it as +necessary. +

+ + + +
+ + + + + + + + + + + +
Back: BackgroundForward: 1. Overview of Scheme   FastBack: IntroductionUp: IntroductionFastForward: 1. Overview of SchemeTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Acknowledgements

+ + +

We would like to thank the following people for their help: Alan Bawden, Michael +Blair, George Carrette, Andy Cromarty, Pavel Curtis, Jeff Dalton, Olivier Danvy, +Ken Dickey, Bruce Duba, Marc Feeley, +Andy Freeman, Richard Gabriel, Yekta G"ursel, Ken Haase, Robert +Hieb, Paul Hudak, Morry Katz, Chris Lindblad, Mark Meyer, Jim Miller, Jim Philbin, +John Ramsdell, Mike Shaff, Jonathan Shapiro, Julie Sussman, +Perry Wagle, Daniel Weise, Henry Wu, and Ozan Yigit. +We thank Carol Fessenden, Daniel +Friedman, and Christopher Haynes for permission to use text from the Scheme 311 +version 4 reference manual. We thank Texas Instruments, Inc. for permission to +use text from the TI Scheme Language Reference Manual[TImanual85]. +We gladly acknowledge the influence of manuals for MIT Scheme[MITScheme], +T[Rees84], Scheme 84[Scheme84],Common Lisp[CLtL], +and Algol 60[Naur63]. +

+

We also thank Betty Dexter for the extreme effort she put into +setting this report in TeX, and Donald Knuth for designing the program +that caused her troubles. +

+

The Artificial Intelligence Laboratory of the +Massachusetts Institute of Technology, the Computer Science +Department of Indiana University, the Computer and Information +Sciences Department of the University of Oregon, and the NEC Research +Institute supported the preparation of this report. Support for the MIT +work was provided in part by +the Advanced Research Projects Agency of the Department of Defense under Office +of Naval Research contract N00014-80-C-0505. Support for the Indiana +University work was provided by NSF grants NCS 83-04567 and NCS +83-03325. +

+ + + +
+
+ + + +
+ + + + + + + + + + + +
Back: AcknowledgementsForward: 1.1 Semantics   FastBack: IntroductionUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1. Overview of Scheme

+ + + + + + + + +
+ + + + + + + + + + + +
Back: 1. Overview of SchemeForward: 1.2 Syntax   FastBack: 1. Overview of SchemeUp: 1. Overview of SchemeFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.1 Semantics

+ + + +

This section gives an overview of Scheme's semantics. A +detailed informal semantics is the subject of +chapters Basic concepts through Standard procedures. For reference +purposes, section Formal semantics provides a formal +semantics of Scheme. +

+

Following Algol, Scheme is a statically scoped programming +language. Each use of a variable is associated with a lexically +apparent binding of that variable. +

+

Scheme has latent as opposed to manifest types. Types +are associated with values (also called objects) rather than + +with variables. (Some authors refer to languages with latent types as +weakly typed or dynamically typed languages.) Other languages with +latent types are APL, Snobol, and other dialects of Lisp. Languages +with manifest types (sometimes referred to as strongly typed or +statically typed languages) include Algol 60, Pascal, and C. +

+

All objects created in the course of a Scheme computation, including +procedures and continuations, have unlimited extent. +No Scheme object is ever destroyed. The reason that +implementations of Scheme do not (usually!) run out of storage is that +they are permitted to reclaim the storage occupied by an object if +they can prove that the object cannot possibly matter to any future +computation. Other languages in which most objects have unlimited +extent include APL and other Lisp dialects. +

+

Implementations of Scheme are required to be properly tail-recursive. +This allows the execution of an iterative computation in constant space, +even if the iterative computation is described by a syntactically +recursive procedure. Thus with a properly tail-recursive implementation, +iteration can be expressed using the ordinary procedure-call +mechanics, so that special iteration constructs are useful only as +syntactic sugar. See section Proper tail recursion. +

+

Scheme procedures are objects in their own right. Procedures can be +created dynamically, stored in data structures, returned as results of +procedures, and so on. Other languages with these properties include +Common Lisp and ML. +

+ +

One distinguishing feature of Scheme is that continuations, which +in most other languages only operate behind the scenes, also have +“first-class” status. Continuations are useful for implementing a +wide variety of advanced control constructs, including non-local exits, +backtracking, and coroutines. See section Control features. +

+

Arguments to Scheme procedures are always passed by value, which +means that the actual argument expressions are evaluated before the +procedure gains control, whether the procedure needs the result of the +evaluation or not. ML, C, and APL are three other languages that always +pass arguments by value. +This is distinct from the lazy-evaluation semantics of Haskell, +or the call-by-name semantics of Algol 60, where an argument +expression is not evaluated unless its value is needed by the +procedure. +

+ + +

Scheme's model of arithmetic is designed to remain as independent as +possible of the particular ways in which numbers are represented within a +computer. In Scheme, every integer is a rational number, every rational is a +real, and every real is a complex number. Thus the distinction between integer +and real arithmetic, so important to many programming languages, does not +appear in Scheme. In its place is a distinction between exact arithmetic, +which corresponds to the mathematical ideal, and inexact arithmetic on +approximations. As in Common Lisp, exact arithmetic is not limited to +integers. +

+
+ + + + + + + + + + + +
Back: 1.1 SemanticsForward: 1.3 Notation and terminology   FastBack: 1. Overview of SchemeUp: 1. Overview of SchemeFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.2 Syntax

+ + +

Scheme, like most dialects of Lisp, employs a fully parenthesized prefix +notation for programs and (other) data; the grammar of Scheme generates a +sublanguage of the language used for data. An important +consequence of this simple, uniform representation is the susceptibility of +Scheme programs and data to uniform treatment by other Scheme programs. +For example, the eval procedure evaluates a Scheme program expressed +as data. +

+

The read procedure performs syntactic as well as lexical decomposition of +the data it reads. The read procedure parses its input as data +(section see section External representations), not as program. +

+

The formal syntax of Scheme is described in section Formal syntax. +

+ +
+ + + + + + + + + + + +
Back: 1.2 SyntaxForward: 1.3.1 Primitive; library; and optional features   FastBack: 1. Overview of SchemeUp: 1. Overview of SchemeFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.3 Notation and terminology

+ + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 1.3 Notation and terminologyForward: 1.3.2 Error situations and unspecified behavior   FastBack: 1. Overview of SchemeUp: 1.3 Notation and terminologyFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.3.1 Primitive; library; and optional features

+ + + +

It is required that every implementation of Scheme support all +features that are not marked as being optional. Implementations are + +free to omit optional features of Scheme or to add extensions, +provided the extensions are not in conflict with the language reported +here. In particular, implementations must support portable code by +providing a syntactic mode that preempts no lexical conventions of this +report. +

+

To aid in understanding and implementing Scheme, some features are marked +as library. These can be easily implemented in terms of the other, + +primitive, features. They are redundant in the strict sense of +the word, but they capture common patterns of usage, and are therefore +provided as convenient abbreviations. +

+
+ + + + + + + + + + + +
Back: 1.3.1 Primitive; library; and optional featuresForward: 1.3.3 Entry format   FastBack: 1. Overview of SchemeUp: 1.3 Notation and terminologyFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.3.2 Error situations and unspecified behavior

+ + + + +

When speaking of an error situation, this report uses the phrase “an +error is signalled” to indicate that implementations must detect and +report the error. If such wording does not appear in the discussion of +an error, then implementations are not required to detect or report the +error, though they are encouraged to do so. An error situation that +implementations are not required to detect is usually referred to simply +as “an error.” +

+

For example, it is an error for a procedure to be passed an argument that +the procedure is not explicitly specified to handle, even though such +domain errors are seldom mentioned in this report. Implementations may +extend a procedure's domain of definition to include such arguments. +

+

This report uses the phrase “may report a violation of an +implementation restriction” to indicate circumstances under which an +implementation is permitted to report that it is unable to continue +execution of a correct program because of some restriction imposed by the +implementation. Implementation restrictions are of course discouraged, +but implementations are encouraged to report violations of implementation +restrictions. + +

+

For example, an implementation may report a violation of an +implementation restriction if it does not have enough storage to run a +program. +

+

If the value of an expression is said to be “unspecified,” then +the expression must evaluate to some object without signalling an error, +but the value depends on the implementation; this report explicitly does +not say what value should be returned. + +

+ + + + + +
+ + + + + + + + + + + +
Back: 1.3.2 Error situations and unspecified behaviorForward: 1.3.4 Evaluation examples   FastBack: 1. Overview of SchemeUp: 1.3 Notation and terminologyFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.3.3 Entry format

+ + +

Chapters Expressions and Standard procedures are organized +into entries. Each entry describes one language feature or a group of +related features, where a feature is either a syntactic construct or a +built-in procedure. An entry begins with one or more header lines of the form +

+ +
templatecategory
+ + +

for required, primitive features, or +

+ +
templatequalifier category
+ + +

where qualifier is either “library” or “optional” as defined + in section Primitive; library; and optional features. +

+

If category is “syntax”, the entry describes an expression +type, and the template gives the syntax of the expression type. +Components of expressions are designated by syntactic variables, which +are written using angle brackets, for example, <expression>, +<variable>. Syntactic variables should be understood to denote segments of +program text; for example, <expression> stands for any string of +characters which is a syntactically valid expression. The notation +

+
 
 <thing1> …
+
+ +

indicates zero or more occurrences of a <thing>, and +

+
 
 <thing1> <thing2> …
+
+ +

indicates one or more occurrences of a <thing>. +

+

If category is “procedure”, then the entry describes a procedure, and +the header line gives a template for a call to the procedure. Argument +names in the template are italicized. Thus the header line +

+ +
(vector-ref vector k)procedure
+ + +

indicates that the built-in procedure vector-ref takes +two arguments, a vector vector and an exact non-negative integer +k (see below). The header lines +

+ + +
(make-vector k)procedure
+
(make-vector k fill)procedure
+ + +

indicate that the make-vector procedure must be defined to take +either one or two arguments. +

+ +

It is an error for an operation to be presented with an argument that it +is not specified to handle. For succinctness, we follow the convention +that if an argument name is also the name of a type listed in +section Disjointness of types, then that argument must be of the named type. +For example, the header line for vector-ref given above dictates that the +first argument to vector-ref must be a vector. The following naming +conventions also imply type restrictions: +

+ +
+
obj
+
+
+

any object +

list, list1, … listj, … +

list (see section see section Pairs and lists) +

z, z1, … zj, … +

complex number +

x, x1, … xj, … +

real number +

y, y1, … yj, … +

real number +

q, q1, … qj, … +

rational number +

n, n1, … nj, … +

integer +

k, k1, … kj, … +

exact non-negative integer +

+ + + + + + + +
+ + + + + + + + + + + +
Back: 1.3.3 Entry formatForward: 1.3.5 Naming conventions   FastBack: 1. Overview of SchemeUp: 1.3 Notation and terminologyFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.3.4 Evaluation examples

+ + +

The symbol “⇒” used in program examples should be read +“evaluates to.” For example, +

+ +
 
+(* 5 8)                                ==>  40
+
+ + +

means that the expression (* 5 8) evaluates to the object 40. +Or, more precisely: the expression given by the sequence of characters +“(* 5 8)” evaluates, in the initial environment, to an object +that may be represented externally by the sequence of characters “40”. See section External representations for a discussion of external +representations of objects. +

+
+ + + + + + + + + + + +
Back: 1.3.4 Evaluation examplesForward: 2. Lexical conventions   FastBack: 1. Overview of SchemeUp: 1.3 Notation and terminologyFastForward: 2. Lexical conventionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

1.3.5 Naming conventions

+ + +

By convention, the names of procedures that always return a boolean +value usually end +in “?”. Such procedures are called predicates. + +

+

By convention, the names of procedures that store values into previously +allocated locations (see section see section Storage model) usually end in +“!”. + +Such procedures are called mutation procedures. +By convention, the value returned by a mutation procedure is unspecified. +

+

By convention, “->” appears within the names of procedures that + +take an object of one type and return an analogous object of another type. +For example, list->vector takes a list and returns a vector whose +elements are the same as those of the list. +

+ + + + + + +
+ + + + + + + + + + + +
Back: 1.3.5 Naming conventionsForward: 2.1 Identifiers   FastBack: 1. Overview of SchemeUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: 3. Basic conceptsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

2. Lexical conventions

+ + + + + + + + +

This section gives an informal account of some of the lexical +conventions used in writing Scheme programs. For a formal syntax of +Scheme, see section Formal syntax. +

+

Upper and lower case forms of a letter are never distinguished +except within character and string constants. For example, Foo is +the same identifier as FOO, and #x1AB is the same number as +#X1ab. +

+
+ + + + + + + + + + + +
Back: 2. Lexical conventionsForward: 2.2 Whitespace and comments   FastBack: 2. Lexical conventionsUp: 2. Lexical conventionsFastForward: 3. Basic conceptsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

2.1 Identifiers

+ + + +

Most identifiers allowed by other programming + +languages are also acceptable to Scheme. The precise rules for forming +identifiers vary among implementations of Scheme, but in all +implementations a sequence of letters, digits, and “extended alphabetic +characters” that begins with a character that cannot begin a number is +an identifier. In addition, +, -, and ... are identifiers. + + + +Here are some examples of identifiers: +

+ +
 
+lambda                   q
+list->vector             soup
++                        V17a
+<=?                      a34kTMNs
+the-word-recursion-has-many-meanings
+
+ + +

Extended alphabetic characters may be used within identifiers as if +they were letters. The following are extended alphabetic characters: +

+ +
 
+! $ % & * + - . / : < = > ? @ ^ _ ~ 
+
+ + +

See section Lexical structure for a formal syntax of identifiers. +

+

Identifiers have two uses within Scheme programs: +

+ + + + + + + + + + +
+ + + + + + + + + + + +
Back: 2.1 IdentifiersForward: 2.3 Other notations   FastBack: 2. Lexical conventionsUp: 2. Lexical conventionsFastForward: 3. Basic conceptsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

2.2 Whitespace and comments

+ + +

Whitespace characters are spaces and newlines. + +(Implementations typically provide additional whitespace characters such +as tab or page break.) Whitespace is used for improved readability and +as necessary to separate tokens from each other, a token being an +indivisible lexical unit such as an identifier or number, but is +otherwise insignificant. Whitespace may occur between any two tokens, +but not within a token. Whitespace may also occur inside a string, +where it is significant. +

+

A semicolon (;) indicates the start of a +comment. The comment continues to the + + +end of the line on which the semicolon appears. Comments are invisible +to Scheme, but the end of the line is visible as whitespace. This +prevents a comment from appearing in the middle of an identifier or +number. +

+ +
 
+;;; The FACT procedure computes the factorial
+;;; of a non-negative integer.
+(define fact
+  (lambda (n)
+    (if (= n 0)
+        1        ;Base case: return 1
+        (* n (fact (- n 1))))))
+
+ + + +
+ + + + + + + + + + + +
Back: 2.2 Whitespace and commentsForward: 3. Basic concepts   FastBack: 2. Lexical conventionsUp: 2. Lexical conventionsFastForward: 3. Basic conceptsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

2.3 Other notations

+ + + + +

For a description of the notations used for numbers, see +section Numbers. +

+ +
+
. + -
+

These are used in numbers, and may also occur anywhere in an identifier +except as the first character. A delimited plus or minus sign by itself +is also an identifier. +A delimited period (not occurring within a number or identifier) is used +in the notation for pairs (section see section Pairs and lists), and to indicate a +rest-parameter in a formal parameter list (section see section Procedures). +A delimited sequence of three successive periods is also an identifier. +

+
+
( )
+

Parentheses are used for grouping and to notate lists +(section see section Pairs and lists). +

+
+
'
+

The single quote character is used to indicate literal data (section see section Literal expressions). +

+
+
+

The backquote character is used to indicate almost-constant +data (section see section Quasiquotation). +

+
+
, ,@
+

The character comma and the sequence comma at-sign are used in conjunction +with backquote (section see section Quasiquotation). +

+
+
"
+

The double quote character is used to delimit strings (section see section Strings). +

+
+
\
+

Backslash is used in the syntax for character constants +(section see section Characters) and as an escape character within string +constants (section see section Strings). +

+ +
+
[ ] { } |
+

Left and right square brackets and curly braces and vertical bar +are reserved for possible future extensions to the language. +

+
+
#
+

Sharp sign is used for a variety of purposes depending on +the character that immediately follows it: +

+
+
#t #f
+

These are the boolean constants (section see section Booleans). +

+
+
#\
+

This introduces a character constant (section see section Characters). +

+
+
#(
+

This introduces a vector constant (section see section Vectors). Vector constants +are terminated by ) . +

+
+
#e #i #b #o #d #x
+

These are used in the notation for numbers (section see section Syntax of numerical constants). +

+
+
+ + + +
+ + + + + + + + + + + +
Back: 2.3 Other notationsForward: 3.1 Variables; syntactic keywords; and regions   FastBack: 2. Lexical conventionsUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: 4. ExpressionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

3. Basic concepts

+ + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 3. Basic conceptsForward: 3.2 Disjointness of types   FastBack: 3. Basic conceptsUp: 3. Basic conceptsFastForward: 4. ExpressionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

3.1 Variables; syntactic keywords; and regions

+ + + + +

An identifier may name a type of syntax, or it may name + +a location where a value can be stored. An identifier that names a type +of syntax is called a syntactic keyword + +and is said to be bound to that syntax. An identifier that names a +location is called a variable and is said to be + +bound to that location. The set of all visible +bindings in effect at some point in a program is + +known as the environment in effect at that point. The value +stored in the location to which a variable is bound is called the +variable's value. By abuse of terminology, the variable is sometimes +said to name the value or to be bound to the value. This is not quite +accurate, but confusion rarely results from this practice. +

+ + + + +

Certain expression types are used to create new kinds of syntax +and bind syntactic keywords to those new syntaxes, while other +expression types create new locations and bind variables to those +locations. These expression types are called binding constructs. +

+ +

Those that bind syntactic keywords are listed in section Macros. +The most fundamental of the variable binding constructs is the +lambda expression, because all other variable binding constructs +can be explained in terms of lambda expressions. The other +variable binding constructs are let, let*, letrec, +and do expressions (see sections see section Procedures, see section Binding constructs, and +see section Iteration). +

+ +

Like Algol and Pascal, and unlike most other dialects of Lisp +except for Common Lisp, Scheme is a statically scoped language with +block structure. To each place where an identifier is bound in a program +there corresponds a region of the program text within which + +the binding is visible. The region is determined by the particular +binding construct that establishes the binding; if the binding is +established by a lambda expression, for example, then its region +is the entire lambda expression. Every mention of an identifier +refers to the binding of the identifier that established the +innermost of the regions containing the use. If there is no binding of +the identifier whose region contains the use, then the use refers to the +binding for the variable in the top level environment, if any +(chapters see section Expressions and see section Standard procedures); if there is no +binding for the identifier, +it is said to be unbound. + + + +

+ + + + + + +
+ + + + + + + + + + + +
Back: 3.1 Variables; syntactic keywords; and regionsForward: 3.3 External representations   FastBack: 3. Basic conceptsUp: 3. Basic conceptsFastForward: 4. ExpressionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

3.2 Disjointness of types

+ + + +

No object satisfies more than one of the following predicates: +

+ +
 
+boolean?          pair?
+symbol?           number?
+char?             string?
+vector?           port?
+procedure?
+
+ + +

These predicates define the types boolean, pair, symbol, number, char (or character), string, vector, port, and procedure. The empty list is a special +object of its own type; it satisfies none of the above predicates. +

+ + + + + + + + + + + + + + +

Although there is a separate boolean type, +any Scheme value can be used as a boolean value for the purpose of a +conditional test. As explained in section Booleans, all +values count as true in such a test except for #f. +This report uses the word “true” to refer to any +Scheme value except #f, and the word “false” to refer to +#f. + + +

+
+ + + + + + + + + + + +
Back: 3.2 Disjointness of typesForward: 3.4 Storage model   FastBack: 3. Basic conceptsUp: 3. Basic conceptsFastForward: 4. ExpressionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

3.3 External representations

+ + + +

An important concept in Scheme (and Lisp) is that of the external +representation of an object as a sequence of characters. For example, +an external representation of the integer 28 is the sequence of +characters “28”, and an external representation of a list consisting +of the integers 8 and 13 is the sequence of characters “(8 13)”. +

+

The external representation of an object is not necessarily unique. The +integer 28 also has representations “#e28.000” and “#x1c”, and the +list in the previous paragraph also has the representations “( 08 13 +)” and “(8 . (13 . ()))” (see section see section Pairs and lists). +

+

Many objects have standard external representations, but some, such as +procedures, do not have standard representations (although particular +implementations may define representations for them). +

+

An external representation may be written in a program to obtain the +corresponding object (see quote, section see section Literal expressions). +

+

External representations can also be used for input and output. The +procedure read (section see section Input) parses external +representations, and the procedure write (section see section Output) +generates them. Together, they provide an elegant and powerful +input/output facility. +

+

Note that the sequence of characters “(+ 2 6)” is not an +external representation of the integer 8, even though it is an +expression evaluating to the integer 8; rather, it is an external +representation of a three-element list, the elements of which are the symbol ++ and the integers 2 and 6. Scheme's syntax has the property that +any sequence of characters that is an expression is also the external +representation of some object. This can lead to confusion, since it may +not be obvious out of context whether a given sequence of characters is +intended to denote data or program, but it is also a source of power, +since it facilitates writing programs such as interpreters and +compilers that treat programs as data (or vice versa). +

+

The syntax of external representations of various kinds of objects +accompanies the description of the primitives for manipulating the +objects in the appropriate sections of chapter Standard procedures. +

+
+ + + + + + + + + + + +
Back: 3.3 External representationsForward: 3.5 Proper tail recursion   FastBack: 3. Basic conceptsUp: 3. Basic conceptsFastForward: 4. ExpressionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

3.4 Storage model

+ + + +

Variables and objects such as pairs, vectors, and strings implicitly +denote locations or sequences of locations. A string, for + +example, denotes as many locations as there are characters in the string. +(These locations need not correspond to a full machine word.) A new value may be +stored into one of these locations using the string-set! procedure, but +the string continues to denote the same locations as before. +

+

An object fetched from a location, by a variable reference or by +a procedure such as car, vector-ref, or string-ref, is +equivalent in the sense of eqv? +(section see section Equivalence predicates) + +to the object last stored in the location before the fetch. +

+

Every location is marked to show whether it is in use. +No variable or object ever refers to a location that is not in use. +Whenever this report speaks of storage being allocated for a variable +or object, what is meant is that an appropriate number of locations are +chosen from the set of locations that are not in use, and the chosen +locations are marked to indicate that they are now in use before the variable +or object is made to denote them. +

+

In many systems it is desirable for constants (i.e. the values of + +literal expressions) to reside in read-only-memory. To express this, it is +convenient to imagine that every object that denotes locations is associated +with a flag telling whether that object is mutable or + +immutable. In such systems literal constants and the strings + +returned by symbol->string are immutable objects, while all objects + +created by the other procedures listed in this report are mutable. It is an +error to attempt to store a new value into a location that is denoted by an +immutable object. +

+
+ + + + + + + + + + + +
Back: 3.4 Storage modelForward: 4. Expressions   FastBack: 3. Basic conceptsUp: 3. Basic conceptsFastForward: 4. ExpressionsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

3.5 Proper tail recursion

+ + + +

Implementations of Scheme are required to be +properly tail-recursive. + +Procedure calls that occur in certain syntactic +contexts defined below are ‘tail calls'. A Scheme implementation is +properly tail-recursive if it supports an unbounded number of active +tail calls. A call is active if the called procedure may still +return. Note that this includes calls that may be returned from either +by the current continuation or by continuations captured earlier by +call-with-current-continuation that are later invoked. +In the absence of captured continuations, calls could +return at most once and the active calls would be those that had not +yet returned. +A formal definition of proper tail recursion can be found +in [propertailrecursion]. +

+ +

Rationale: +

+

Intuitively, no space is needed for an active tail call because the +continuation that is used in the tail call has the same semantics as the +continuation passed to the procedure containing the call. Although an improper +implementation might use a new continuation in the call, a return +to this new continuation would be followed immediately by a return +to the continuation passed to the procedure. A properly tail-recursive +implementation returns to that continuation directly. +

+

Proper tail recursion was one of the central ideas in Steele and +Sussman's original version of Scheme. Their first Scheme interpreter +implemented both functions and actors. Control flow was expressed using +actors, which differed from functions in that they passed their results +on to another actor instead of returning to a caller. In the terminology +of this section, each actor finished with a tail call to another actor. +

+

Steele and Sussman later observed that in their interpreter the code +for dealing with actors was identical to that for functions and thus +there was no need to include both in the language. +

+
+ + +

A tail call is a procedure call that occurs + +in a tail context. Tail contexts are defined inductively. Note +that a tail context is always determined with respect to a particular lambda +expression. +

+ + +
    +
  • +The last expression within the body of a lambda expression, +shown as <tail expression> below, occurs in a tail context. + +
     
    (lambda <formals>
    +  <definition>* <expression>* <tail expression>)
    +
    + + + +
  • +If one of the following expressions is in a tail context, +then the subexpressions shown as <tail expression> are in a tail context. +These were derived from rules in the grammar given in +chapter Formal syntax and semantics by replacing some occurrences of <expression> +with <tail expression>. Only those rules that contain tail contexts +are shown here. + + +
     
    (if <expression> <tail expression> <tail expression>)
    +(if <expression> <tail expression>)
    +
    +(cond <cond clause>+)
    +(cond <cond clause>* (else <tail sequence>))
    +
    +(case <expression>
    +  <case clause>+)
    +(case <expression>
    +  <case clause>*
    +  (else <tail sequence>))
    +
    +(and <expression>* <tail expression>)
    +(or <expression>* <tail expression>)
    +
    +(let (<binding spec>*) <tail body>)
    +(let <variable> (<binding spec>*) <tail body>)
    +(let* (<binding spec>*) <tail body>)
    +(letrec (<binding spec>*) <tail body>)
    +
    +(let-syntax (<syntax spec>*) <tail body>)
    +(letrec-syntax (<syntax spec>*) <tail body>)
    +
    +(begin <tail sequence>)
    +
    +(do (<iteration spec>*)
    +    (<test> <tail sequence>)
    +  <expression>*)
    +
    +where
    +
    +<cond clause> –> (<test> <tail sequence>)
    +<case clause> –> ((<datum>*) <tail sequence>)
    +
    +<tail body> –> <definition>* <tail sequence>
    +<tail sequence> –> <expression>* <tail expression>
    +
    + + + +
  • +If a cond expression is in a tail context, and has a clause of +the form (<expression1> => <expression2>) +then the (implied) call to +the procedure that results from the evaluation of <expression2> is in a +tail context. <expression2> itself is not in a tail context. + + +
+ + +

Certain built-in procedures are also required to perform tail calls. +The first argument passed to apply and to + +call-with-current-continuation, and the second argument passed to + +call-with-values, must be called via a tail call. + +Similarly, eval must evaluate its argument as if it + +were in tail position within the eval procedure. + +

+

In the following example the only tail call is the call to f. +None of the calls to g or h are tail calls. The reference to +x is in a tail context, but it is not a call and thus is not a +tail call. +

+
 
+(lambda ()
+  (if (g)
+      (let ((x (h)))
+        x)
+      (and (g) (f))))
+
+ + + +

Note: +Implementations are allowed, but not required, to +recognize that some non-tail calls, such as the call to h +above, can be evaluated as though they were tail calls. +In the example above, the let expression could be compiled +as a tail call to h. (The possibility of h returning +an unexpected number of values can be ignored, because in that +case the effect of the let is explicitly unspecified and +implementation-dependent.) +

+ + + + +
+ + + + + + + + + + + +
Back: 3.5 Proper tail recursionForward: 4.1 Primitive expression types   FastBack: 3. Basic conceptsUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4. Expressions

+ + + + + + + + + + + +

Expression types are categorized as primitive or derived. +Primitive expression types include variables and procedure calls. +Derived expression types are not semantically primitive, but can instead +be defined as macros. +With the exception of quasiquote, whose macro definition is complex, +the derived expressions are classified as library features. +Suitable definitions are given in section Derived expression types. +

+
+ + + + + + + + + + + +
Back: 4. ExpressionsForward: 4.1.1 Variable references   FastBack: 4. ExpressionsUp: 4. ExpressionsFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.1 Primitive expression types

+ + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: 4.1 Primitive expression typesForward: 4.1.2 Literal expressions   FastBack: 4. ExpressionsUp: 4.1 Primitive expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.1.1 Variable references

+ + + +
<variable>syntax
+ + +

An expression consisting of a variable + +(section see section Variables; syntactic keywords; and regions) is a variable reference. The value of +the variable reference is the value stored in the location to which the +variable is bound. It is an error to reference an +unbound variable. + +

+ +
 
(define x 28)
+x                                      ==>  28
+
+ + + +
+ + + + + + + + + + + +
Back: 4.1.1 Variable referencesForward: 4.1.3 Procedure calls   FastBack: 4. ExpressionsUp: 4.1 Primitive expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.1.2 Literal expressions

+ + + + +
(quote <datum>)syntax
+
'<datum>syntax
+
<constant>syntax
+ + +

(quote <datum>) evaluates to <datum>. + +<Datum> +may be any external representation of a Scheme object (see +section see section External representations). This notation is used to include literal +constants in Scheme code. +

+ +
 
+(quote a)                              ==>  a
+(quote #(a b c))                       ==>  #(a b c)
+(quote (+ 1 2))                        ==>  (+ 1 2)
+
+ + +

(quote <datum>) may be abbreviated as +'<datum>. The two notations are equivalent in all +respects. +

+ +
 
'a                                     ==>  a
+'#(a b c)                              ==>  #(a b c)
+'()                                    ==>  ()
+'(+ 1 2)                               ==>  (+ 1 2)
+'(quote a)                             ==>  (quote a)
+''a                                    ==>  (quote a)
+
+ + +

Numerical constants, string constants, character constants, and boolean +constants evaluate “to themselves”; they need not be quoted. +

+ +
 
'"abc"                                 ==>  "abc"
+"abc"                                  ==>  "abc"
+'145932                                ==>  145932
+145932                                 ==>  145932
+'#t                                    ==>  #t
+#t                                     ==>  #t
+
+ + +

As noted in section Storage model, it is an error to alter a constant +(i.e. the value of a literal expression) using a mutation procedure like +set-car! or string-set!. +

+ + + +
+ + + + + + + + + + + +
Back: 4.1.2 Literal expressionsForward: 4.1.4 Procedures   FastBack: 4. ExpressionsUp: 4.1 Primitive expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.1.3 Procedure calls

+ + + +
(<operator> <operand1>)syntax
+ + +

A procedure call is written by simply enclosing in parentheses +expressions for the procedure to be called and the arguments to be +passed to it. The operator and operand expressions are evaluated (in an +unspecified order) and the resulting procedure is passed the resulting +arguments. + + +

+
 
(+ 3 4)                                ==>  7
+((if #f + *) 3 4)                      ==>  12
+
+ + +

A number of procedures are available as the values of variables in the +initial environment; for example, the addition and multiplication +procedures in the above examples are the values of the variables + +and *. New procedures are created by evaluating lambda expressions +(see section see section Procedures). +

+ +

Procedure calls may return any number of values (see values in + +section see section Control features). With the exception of values +the procedures available in the initial environment return one +value or, for procedures such as apply, pass on the values returned +by a call to one of their arguments. +

+

Procedure calls are also called combinations. +

+ + + +

Note: In contrast to other dialects of Lisp, the order of +evaluation is unspecified, and the operator expression and the operand +expressions are always evaluated with the same evaluation rules. +

+ + + +

Note: +Although the order of evaluation is otherwise unspecified, the effect of +any concurrent evaluation of the operator and operand expressions is +constrained to be consistent with some sequential order of evaluation. +The order of evaluation may be chosen differently for each procedure call. +

+ + + +

Note: In many dialects of Lisp, the empty combination, (), is a legitimate expression. In Scheme, combinations must have at +least one subexpression, so () is not a syntactically valid +expression. +

+
+ + + + + + + +
+ + + + + + + + + + + +
Back: 4.1.3 Procedure callsForward: 4.1.5 Conditionals   FastBack: 4. ExpressionsUp: 4.1 Primitive expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.1.4 Procedures

+ + + + +
(lambda <formals> <body>)syntax
+ +

Syntax: +<Formals> should be a formal arguments list as described below, +and <body> should be a sequence of one or more expressions. +

+

Semantics: +A lambda expression evaluates to a procedure. The environment in +effect when the lambda expression was evaluated is remembered as part of the +procedure. When the procedure is later called with some actual +arguments, the environment in which the lambda expression was evaluated will +be extended by binding the variables in the formal argument list to +fresh locations, the corresponding actual argument values will be stored +in those locations, and the expressions in the body of the lambda expression +will be evaluated sequentially in the extended environment. +The result(s) of the last expression in the body will be returned as +the result(s) of the procedure call. +

+ +
 
(lambda (x) (+ x x))                   ==>  a procedure
+((lambda (x) (+ x x)) 4)               ==>  8
+
+(define reverse-subtract
+  (lambda (x y) (- y x)))
+(reverse-subtract 7 10)                ==>  3
+
+(define add4
+  (let ((x 4))
+    (lambda (y) (+ x y))))
+(add4 6)                               ==>  10
+
+ + +

<Formals> should have one of the following forms: +

+ + +
    +
  • +(<variable1> …): +The procedure takes a fixed number of arguments; when the procedure is +called, the arguments will be stored in the bindings of the +corresponding variables. + +
  • +<variable>: +The procedure takes any number of arguments; when the procedure is +called, the sequence of actual arguments is converted into a newly +allocated list, and the list is stored in the binding of the +<variable>. + +
  • +(<variable1><variable_n> . +<variable_n+1>): +If a space-delimited period precedes the last variable, then +the procedure takes n or more arguments, where n is the +number of formal arguments before the period (there must +be at least one). +The value stored in the binding of the last variable will be a +newly allocated +list of the actual arguments left over after all the other actual +arguments have been matched up against the other formal arguments. + +
+ + +

It is an error for a <variable> to appear more than once in +<formals>. +

+ +
 
((lambda x x) 3 4 5 6)                 ==>  (3 4 5 6)
+((lambda (x y . z) z)
+ 3 4 5 6)                              ==>  (5 6)
+
+ + +

Each procedure created as the result of evaluating a lambda expression is +(conceptually) tagged +with a storage location, in order to make eqv? and + +eq? work on procedures (see section see section Equivalence predicates). + +

+ + + +
+ + + + + + + + + + + +
Back: 4.1.4 ProceduresForward: 4.1.6 Assignments   FastBack: 4. ExpressionsUp: 4.1 Primitive expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.1.5 Conditionals

+ + + +
(if <test> <consequent> <alternate>)syntax
+
(if <test> <consequent>)syntax
+ +

Syntax: +<Test>, <consequent>, and <alternate> may be arbitrary +expressions. +

+

Semantics: +An if expression is evaluated as follows: first, +<test> is evaluated. If it yields a true value (see + +section see section Booleans), then <consequent> is evaluated and +its value(s) is(are) returned. Otherwise <alternate> is evaluated and its +value(s) is(are) returned. If <test> yields a false value and no +<alternate> is specified, then the result of the expression is +unspecified. +

+ +
 
(if (> 3 2) 'yes 'no)                  ==>  yes
+(if (> 2 3) 'yes 'no)                  ==>  no
+(if (> 3 2)
+    (- 3 2)
+    (+ 3 2))                           ==>  1
+
+ + + + + +
+ + + + + + + + + + + +
Back: 4.1.5 ConditionalsForward: 4.2 Derived expression types   FastBack: 4. ExpressionsUp: 4.1 Primitive expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.1.6 Assignments

+ + + + +
(set! <variable> <expression>)syntax
+ +

<Expression> is evaluated, and the resulting value is stored in +the location to which <variable> is bound. <Variable> must +be bound either in some region enclosing the set! expression + +or at top level. The result of the set! expression is +unspecified. +

+ +
 
(define x 2)
+(+ x 1)                                ==>  3
+(set! x 4)                             ==>  unspecified
+(+ x 1)                                ==>  5
+
+ + + + + +
+ + + + + + + + + + + +
Back: 4.1.6 AssignmentsForward: 4.2.1 Conditionals   FastBack: 4. ExpressionsUp: 4. ExpressionsFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.2 Derived expression types

+ + + + + + + + + + + + +

The constructs in this section are hygienic, as discussed in +section Macros. +For reference purposes, section Derived expression types gives macro definitions +that will convert most of the constructs described in this section +into the primitive constructs described in the previous section. +

+ + +
+ + + + + + + + + + + +
Back: 4.2 Derived expression typesForward: 4.2.2 Binding constructs   FastBack: 4. ExpressionsUp: 4.2 Derived expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.2.1 Conditionals

+ + + +
(cond <clause1> <clause2> …)library syntax
+ +

Syntax: +Each <clause> should be of the form +

+
 
(<test> <expression1> …)
+
+ +

where <test> is any expression. Alternatively, a <clause> may be +of the form +

+
 
(<test> => <expression>)
+
+ +

The last <clause> may be +an “else clause,” which has the form +

+
 
(else <expression1> <expression2> …).
+
+ + + + + + +

Semantics: +A cond expression is evaluated by evaluating the <test> +expressions of successive <clause>s in order until one of them +evaluates to a true value (see + +section see section Booleans). When a <test> evaluates to a true +value, then the remaining <expression>s in its <clause> are +evaluated in order, and the result(s) of the last <expression> in the +<clause> is(are) returned as the result(s) of the entire cond +expression. If the selected <clause> contains only the +<test> and no <expression>s, then the value of the +<test> is returned as the result. If the selected <clause> uses the +=> alternate form, then the <expression> is evaluated. + +Its value must be a procedure that accepts one argument; this procedure is then +called on the value of the <test> and the value(s) returned by this +procedure is(are) returned by the cond expression. +If all <test>s evaluate +to false values, and there is no else clause, then the result of +the conditional expression is unspecified; if there is an else +clause, then its <expression>s are evaluated, and the value(s) of +the last one is(are) returned. +

+ +
 
(cond ((> 3 2) 'greater)
+      ((< 3 2) 'less))                 ==>  greater
+
+(cond ((> 3 3) 'greater)
+      ((< 3 3) 'less)
+      (else 'equal))                   ==>  equal
+
+(cond ((assv 'b '((a 1) (b 2))) => cadr)
+      (else #f))                       ==>  2
+
+ + + + + + + +
(case <key> <clause1> <clause2> …)library syntax
+ +

Syntax: +<Key> may be any expression. Each <clause> should have +the form +

+
 
((<datum1> …) <expression1> <expression2> …),
+
+ +

where each <datum> is an external representation of some object. +All the <datum>s must be distinct. +The last <clause> may be an “else clause,” which has the form +

+
 
(else <expression1> <expression2> …).
+
+ + + + +

Semantics: +A case expression is evaluated as follows. <Key> is +evaluated and its result is compared against each <datum>. If the +result of evaluating <key> is equivalent (in the sense of +eqv?; see section see section Equivalence predicates) to a <datum>, then the +expressions in the corresponding <clause> are evaluated from left +to right and the result(s) of the last expression in the <clause> is(are) +returned as the result(s) of the case expression. If the result of +evaluating <key> is different from every <datum>, then if +there is an else clause its expressions are evaluated and the +result(s) of the last is(are) the result(s) of the case expression; +otherwise the result of the case expression is unspecified. +

+ +
 
(case (* 2 3)
+  ((2 3 5 7) 'prime)
+  ((1 4 6 8 9) 'composite))            ==>  composite
+(case (car '(c d))
+  ((a) 'a)
+  ((b) 'b))                            ==>  unspecified
+(case (car '(c d))
+  ((a e i o u) 'vowel)
+  ((w y) 'semivowel)
+  (else 'consonant))                   ==>  consonant
+
+ + + + + + +
(and <test1> …)library syntax
+ +

The <test> expressions are evaluated from left to right, and the +value of the first expression that evaluates to a false value (see +section see section Booleans) is returned. Any remaining expressions +are not evaluated. If all the expressions evaluate to true values, the +value of the last expression is returned. If there are no expressions +then #t is returned. +

+ +
 
(and (= 2 2) (> 2 1))                  ==>  #t
+(and (= 2 2) (< 2 1))                  ==>  #f
+(and 1 2 'c '(f g))                    ==>  (f g)
+(and)                                  ==>  #t
+
+ + + + + + +
(or <test1> …)library syntax
+ +

The <test> expressions are evaluated from left to right, and the value of the +first expression that evaluates to a true value (see +section see section Booleans) is returned. Any remaining expressions +are not evaluated. If all expressions evaluate to false values, the +value of the last expression is returned. If there are no +expressions then #f is returned. +

+ +
 
(or (= 2 2) (> 2 1))                   ==>  #t
+(or (= 2 2) (< 2 1))                   ==>  #t
+(or #f #f #f)                          ==>  #f
+(or (memq 'b '(a b c)) 
+    (/ 3 0))                           ==>  (b c)
+
+ + + + + +
+ + + + + + + + + + + +
Back: 4.2.1 ConditionalsForward: 4.2.3 Sequencing   FastBack: 4. ExpressionsUp: 4.2 Derived expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.2.2 Binding constructs

+ + +

The three binding constructs let, let*, and letrec +give Scheme a block structure, like Algol 60. The syntax of the three +constructs is identical, but they differ in the regions they establish + +for their variable bindings. In a let expression, the initial +values are computed before any of the variables become bound; in a +let* expression, the bindings and evaluations are performed +sequentially; while in a letrec expression, all the bindings are in +effect while their initial values are being computed, thus allowing +mutually recursive definitions. +

+ +
(let <bindings> <body>)library syntax
+ +

Syntax: +<Bindings> should have the form +

+
 
((<variable1> <init1>) …),
+
+ +

where each <init> is an expression, and <body> should be a +sequence of one or more expressions. It is +an error for a <variable> to appear more than once in the list of variables +being bound. +

+

Semantics: +The <init>s are evaluated in the current environment (in some +unspecified order), the <variable>s are bound to fresh locations +holding the results, the <body> is evaluated in the extended +environment, and the value(s) of the last expression of <body> +is(are) returned. Each binding of a <variable> has <body> as its +region. + +

+ +
 
(let ((x 2) (y 3))
+  (* x y))                             ==>  6
+
+(let ((x 2) (y 3))
+  (let ((x 7)
+        (z (+ x y)))
+    (* z x)))                          ==>  35
+
+ + +

See also named let, section Iteration. +

+ + + + +
(let* <bindings> <body>)library syntax
+ + +

Syntax: +<Bindings> should have the form +

+
 
((<variable1> <init1>) …),
+
+ +

and <body> should be a sequence of +one or more expressions. +

+

Semantics: +Let* is similar to let, but the bindings are performed +sequentially from left to right, and the region of a binding indicated + +by (<variable> <init>) is that part of the let* +expression to the right of the binding. Thus the second binding is done +in an environment in which the first binding is visible, and so on. +

+ +
 
(let ((x 2) (y 3))
+  (let* ((x 7)
+         (z (+ x y)))
+    (* z x)))                          ==>  70
+
+ + + + + + +
(letrec <bindings> <body>)library syntax
+ +

Syntax: +<Bindings> should have the form +

+
 
((<variable1> <init1>) …),
+
+ +

and <body> should be a sequence of +one or more expressions. It is an error for a <variable> to appear more +than once in the list of variables being bound. +

+

Semantics: +The <variable>s are bound to fresh locations holding undefined +values, the <init>s are evaluated in the resulting environment (in +some unspecified order), each <variable> is assigned to the result +of the corresponding <init>, the <body> is evaluated in the +resulting environment, and the value(s) of the last expression in +<body> is(are) returned. Each binding of a <variable> has the +entire letrec expression as its region, making it possible to + +define mutually recursive procedures. +

+ +
 
(letrec ((even?
+          (lambda (n)
+            (if (zero? n)
+                #t
+                (odd? (- n 1)))))
+         (odd?
+          (lambda (n)
+            (if (zero? n)
+                #f
+                (even? (- n 1))))))
+  (even? 88))   
+                                       ==>  #t
+
+ + +

One restriction on letrec is very important: it must be possible +to evaluate each <init> without assigning or referring to the value of any +<variable>. If this restriction is violated, then it is an error. The +restriction is necessary because Scheme passes arguments by value rather than by +name. In the most common uses of letrec, all the <init>s are +lambda expressions and the restriction is satisfied automatically. +

+ + + + +
+ + + + + + + + + + + +
Back: 4.2.2 Binding constructsForward: 4.2.4 Iteration   FastBack: 4. ExpressionsUp: 4.2 Derived expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.2.3 Sequencing

+ + + +
(begin <expression1> <expression2> …)library syntax
+ +

The <expression>s are evaluated sequentially from left to right, +and the value(s) of the last <expression> is(are) returned. This +expression type is used to sequence side effects such as input and +output. +

+ +
 
(define x 0)
+
+(begin (set! x 5)
+       (+ x 1))                        ==>  6
+
+(begin (display "4 plus 1 equals ")
+       (display (+ 4 1)))              ==>  unspecified
+          and prints  4 plus 1 equals 5
+
+ + + + + +
+ + + + + + + + + + + +
Back: 4.2.3 SequencingForward: 4.2.5 Delayed evaluation   FastBack: 4. ExpressionsUp: 4.2 Derived expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.2.4 Iteration

+ + + + +
(do ((<variable1> <init1> <step1>) …) (<test> <expression> …) <command>)library syntax
+ + +

Do is an iteration construct. It specifies a set of variables to +be bound, how they are to be initialized at the start, and how they are +to be updated on each iteration. When a termination condition is met, +the loop exits after evaluating the <expression>s. +

+

Do expressions are evaluated as follows: +The <init> expressions are evaluated (in some unspecified order), +the <variable>s are bound to fresh locations, the results of the +<init> expressions are stored in the bindings of the +<variable>s, and then the iteration phase begins. +

+

Each iteration begins by evaluating <test>; if the result is +false (see section see section Booleans), then the <command> +expressions are evaluated in order for effect, the <step> +expressions are evaluated in some unspecified order, the +<variable>s are bound to fresh locations, the results of the +<step>s are stored in the bindings of the +<variable>s, and the next iteration begins. +

+

If <test> evaluates to a true value, then the +<expression>s are evaluated from left to right and the value(s) of +the last <expression> is(are) returned. If no <expression>s +are present, then the value of the do expression is unspecified. +

+

The region of the binding of a <variable> + +consists of the entire do expression except for the <init>s. +It is an error for a <variable> to appear more than once in the +list of do variables. +

+

A <step> may be omitted, in which case the effect is the +same as if (<variable> <init> <variable>) had +been written instead of (<variable> <init>). +

+ +
 
(do ((vec (make-vector 5))
+     (i 0 (+ i 1)))
+    ((= i 5) vec)
+  (vector-set! vec i i))               ==>  #(0 1 2 3 4)
+
+(let ((x '(1 3 5 7 9)))
+  (do ((x x (cdr x))
+       (sum 0 (+ sum (car x))))
+      ((null? x) sum)))                ==>  25
+
+ + + + + +
(let <variable> <bindings> <body>)library syntax
+ + +

“Named let” is a variant on the syntax of let which provides + +a more general looping construct than do and may also be used to express +recursions. +It has the same syntax and semantics as ordinary let +except that <variable> is bound within <body> to a procedure +whose formal arguments are the bound variables and whose body is +<body>. Thus the execution of <body> may be repeated by +invoking the procedure named by <variable>. +

+ +
 
(let loop ((numbers '(3 -2 1 6 -5))
+           (nonneg '())
+           (neg '()))
+  (cond ((null? numbers) (list nonneg neg))
+        ((>= (car numbers) 0)
+         (loop (cdr numbers)
+               (cons (car numbers) nonneg)
+               neg))
+        ((< (car numbers) 0)
+         (loop (cdr numbers)
+               nonneg
+               (cons (car numbers) neg)))))   
+          ==>  ((6 1 3) (-5 -2))
+
+ + + + + +
+ + + + + + + + + + + +
Back: 4.2.4 IterationForward: 4.2.6 Quasiquotation   FastBack: 4. ExpressionsUp: 4.2 Derived expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.2.5 Delayed evaluation

+ + + +
(delay <expression>)library syntax
+ + + +

The delay construct is used together with the procedure force to + +implement lazy evaluation or call by need. + + +(delay <expression>) returns an object called a +promise which at some point in the future may be asked (by + +the force procedure) + to evaluate +<expression>, and deliver the resulting value. +The effect of <expression> returning multiple values +is unspecified. +

+

See the description of force (section see section Control features) for a +more complete description of delay. +

+ + + +
+ + + + + + + + + + + +
Back: 4.2.5 Delayed evaluationForward: 4.3 Macros   FastBack: 4. ExpressionsUp: 4.2 Derived expression typesFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.2.6 Quasiquotation

+ + + + +
(quasiquote <qq template>)syntax
+
(`<qq template>)syntax
+ + +

“Backquote” or “quasiquote” expressions are useful + +for constructing a list or vector structure when most but not all of the +desired structure is known in advance. If no +commas appear within the <qq template>, the result of + +evaluating +<qq template> is equivalent to the result of evaluating +'<qq template>. If a comma appears within the + +<qq template>, however, the expression following the comma is +evaluated (“unquoted”) and its result is inserted into the structure +instead of the comma and the expression. If a comma appears followed +immediately by an at-sign (@), then the following + +expression must evaluate to a list; the opening and closing parentheses +of the list are then “stripped away” and the elements of the list are +inserted in place of the comma at-sign expression sequence. A comma +at-sign should only appear within a list or vector <qq template>. +

+ + +
 
‘(list ,(+ 1 2) 4)                     ==>  (list 3 4)
+(let ((name 'a)) ‘(list ,name ',name))           
+          ==>  (list a (quote a))
+‘(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)           
+          ==>  (a 3 4 5 6 b)
+‘((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))           
+          ==>  ((foo 7) . cons)
+‘#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)           
+          ==>  #(10 5 2 4 3 8)
+
+ + +

Quasiquote forms may be nested. Substitutions are made only for +unquoted components appearing at the same nesting level +as the outermost backquote. The nesting level increases by one inside +each successive quasiquotation, and decreases by one inside each +unquotation. +

+ +
 
‘(a ‘(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)           
+          ==>  (a ‘(b ,(+ 1 2) ,(foo 4 d) e) f)
+(let ((name1 'x)
+      (name2 'y))
+  ‘(a ‘(b ,,name1 ,',name2 d) e))           
+          ==>  (a ‘(b ,x ,'y d) e)
+
+ + +

The two notations + <qq template> and (quasiquote <qq template>) + are identical in all respects. + ,<expression> is identical to (unquote <expression>), + and + ,@<expression> is identical to (unquote-splicing <expression>). +The external syntax generated by write for two-element lists whose + +car is one of these symbols may vary between implementations. +

+ + + +
 
(quasiquote (list (unquote (+ 1 2)) 4))           
+          ==>  (list 3 4)
+'(quasiquote (list (unquote (+ 1 2)) 4))           
+          ==>  ‘(list ,(+ 1 2) 4)
+     i.e., (quasiquote (list (unquote (+ 1 2)) 4))
+
+ + +

Unpredictable behavior can result if any of the symbols +quasiquote, unquote, or unquote-splicing appear in + + + +positions within a <qq template> otherwise than as described above. +

+ + +
+ + + + + + + + + + + +
Back: 4.2.6 QuasiquotationForward: 4.3.1 Binding constructs for syntactic keywords   FastBack: 4. ExpressionsUp: 4. ExpressionsFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.3 Macros

+ + + + + + + + +

Scheme programs can define and use new derived expression types, + called macros. + +Program-defined expression types have the syntax +

+
 
+(<keyword> <datum> ...)
+
+ +

where <keyword> is an identifier that uniquely determines the +expression type. This identifier is called the syntactic +keyword, or simply keyword, of the macro. The + + + +number of the <datum>s, and their syntax, depends on the +expression type. +

+

Each instance of a macro is called a use + +of the macro. +The set of rules that specifies +how a use of a macro is transcribed into a more primitive expression +is called the transformer + +of the macro. +

+

The macro definition facility consists of two parts: +

+ + +
    +
  • +A set of expressions used to establish that certain identifiers +are macro keywords, associate them with macro transformers, and control +the scope within which a macro is defined, and + +
  • +a pattern language for specifying macro transformers. + +
+ + +

The syntactic keyword of a macro may shadow variable bindings, and local +variable bindings may shadow keyword bindings. All macros + +defined using the pattern language are “hygienic” and “referentially +transparent” and thus preserve Scheme's lexical scoping [Kohlbecker86], [ +hygienic], [Bawden88], [macrosthatwork], [syntacticabstraction]: +

+ + + + + + + +
    +
  • +If a macro transformer inserts a binding for an identifier +(variable or keyword), the identifier will in effect be renamed +throughout its scope to avoid conflicts with other identifiers. +Note that a define at top level may or may not introduce a binding; +see section Definitions. + +
  • +If a macro transformer inserts a free reference to an +identifier, the reference refers to the binding that was visible +where the transformer was specified, regardless of any local +bindings that may surround the use of the macro. + + +
+ + + + + +
+ + + + + + + + + + + +
Back: 4.3 MacrosForward: 4.3.2 Pattern language   FastBack: 4. ExpressionsUp: 4.3 MacrosFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.3.1 Binding constructs for syntactic keywords

+ + + +

Let-syntax and letrec-syntax are +analogous to let and letrec, but they bind +syntactic keywords to macro transformers instead of binding variables +to locations that contain values. Syntactic keywords may also be +bound at top level; see section Syntax definitions. +

+ +
(let-syntax <bindings> <body>)syntax
+ +

Syntax: +<Bindings> should have the form +

+
 
((<keyword> <transformer spec>) …)
+
+ +

Each <keyword> is an identifier, +each <transformer spec> is an instance of syntax-rules, and +<body> should be a sequence of one or more expressions. It is an error +for a <keyword> to appear more than once in the list of keywords +being bound. +

+

Semantics: +The <body> is expanded in the syntactic environment +obtained by extending the syntactic environment of the +let-syntax expression with macros whose keywords are +the <keyword>s, bound to the specified transformers. +Each binding of a <keyword> has <body> as its region. +

+ +
 
(let-syntax ((when (syntax-rules ()
+                     ((when test stmt1 stmt2 ...)
+                      (if test
+                          (begin stmt1
+                                 stmt2 ...))))))
+  (let ((if #t))
+    (when if (set! if 'now))
+    if))                               ==>  now
+
+(let ((x 'outer))
+  (let-syntax ((m (syntax-rules () ((m) x))))
+    (let ((x 'inner))
+      (m))))                           ==>  outer
+
+ + + + + +
(letrec-syntax <bindings> <body>)syntax
+ +

Syntax: +Same as for let-syntax. +

+

Semantics: + The <body> is expanded in the syntactic environment obtained by +extending the syntactic environment of the letrec-syntax +expression with macros whose keywords are the +<keyword>s, bound to the specified transformers. +Each binding of a <keyword> has the <bindings> +as well as the <body> within its region, +so the transformers can +transcribe expressions into uses of the macros +introduced by the letrec-syntax expression. +

+ +
 
(letrec-syntax
+  ((my-or (syntax-rules ()
+            ((my-or) #f)
+            ((my-or e) e)
+            ((my-or e1 e2 ...)
+             (let ((temp e1))
+               (if temp
+                   temp
+                   (my-or e2 ...)))))))
+  (let ((x #f)
+        (y 7)
+        (temp 8)
+        (let odd?)
+        (if even?))
+    (my-or x
+           (let temp)
+           (if y)
+           y)))                        ==>  7
+
+ + + + +
+ + + + + + + + + + + +
Back: 4.3.1 Binding constructs for syntactic keywordsForward: 5. Program structure   FastBack: 4. ExpressionsUp: 4.3 MacrosFastForward: 5. Program structureTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

4.3.2 Pattern language

+ + + +

A <transformer spec> has the following form: +

+ +
(syntax-rules <literals> <syntax rule>)
+ +

Syntax: +<Literals> is a list of identifiers and each <syntax rule> +should be of the form +

+
 
(<pattern> <template>)
+
+ +

The <pattern> in a <syntax rule> is a list <pattern> +that begins with the keyword for the macro. +

+

A <pattern> is either an identifier, a constant, or one of the +following +

+
 
(<pattern> …)
+(<pattern> <pattern> … . <pattern>)
+(<pattern><pattern> <ellipsis>)
+#(<pattern> …)
+#(<pattern><pattern> <ellipsis>)
+
+ +

and a template is either an identifier, a constant, or one of the following +

+
 
(<element> …)
+(<element> <element> … . <template>)
+#(<element> …)
+
+ +

where an <element> is a <template> optionally +followed by an <ellipsis> and +an <ellipsis> is the identifier “...” (which cannot be used as +an identifier in either a template or a pattern). + +

+

Semantics: An instance of syntax-rules produces a new macro +transformer by specifying a sequence of hygienic rewrite rules. A use +of a macro whose keyword is associated with a transformer specified by +syntax-rules is matched against the patterns contained in the +<syntax rule>s, beginning with the leftmost <syntax rule>. +When a match is found, the macro use is transcribed hygienically +according to the template. +

+

An identifier that appears in the pattern of a <syntax rule> is +a pattern variable, unless it is the keyword that begins the pattern, +is listed in <literals>, or is the identifier “...”. +Pattern variables match arbitrary input elements and +are used to refer to elements of the input in the template. It is an +error for the same pattern variable to appear more than once in a +<pattern>. +

+

The keyword at the beginning of the pattern in a +<syntax rule> is not involved in the matching and +is not considered a pattern variable or literal identifier. +

+ +

Rationale: +The scope of the keyword is determined by the expression or syntax +definition that binds it to the associated macro transformer. +If the keyword were a pattern variable or literal +identifier, then +the template that follows the pattern would be within its scope +regardless of whether the keyword were bound by let-syntax +or by letrec-syntax. +

+ + +

Identifiers that appear in <literals> are interpreted as literal +identifiers to be matched against corresponding subforms of the input. +A subform +in the input matches a literal identifier if and only if it is an +identifier +and either both its occurrence in the macro expression and its +occurrence in the macro definition have the same lexical binding, or +the two identifiers are equal and both have no lexical binding. +

+ +

A subpattern followed by ... can match zero or more elements of the +input. It is an error for ... to appear in <literals>. +Within a pattern the identifier ... must follow the last element of +a nonempty sequence of subpatterns. +

+

More formally, an input form F matches a pattern P if and only if: +

+ + +
    +
  • +P is a non-literal identifier; or + +
  • +P is a literal identifier and F is an identifier with the same +binding; or + +
  • +P is a list (P_1 … P_n) and F is a +list of n +forms that match P_1 through P_n, respectively; or + +
  • +P is an improper list +(P_1 P_2 … P_n . P_n+1) +and F is a list or +improper list of n or more forms that match P_1 through P_n, +respectively, and whose nth “cdr” matches P_n+1; or + +
  • +P is of the form +(P_1 … P_n P_n+1 <ellipsis>) +where <ellipsis> is the identifier ... +and F is +a proper list of at least n forms, the first n of which match +P_1 through P_n, respectively, and each remaining element of F +matches P_n+1; or + +
  • +P is a vector of the form #(P_1 … P_n) +and F is a vector +of n forms that match P_1 through P_n; or + +
  • +P is of the form +#(P_1 … P_n P_n+1 <ellipsis>) +where <ellipsis> is the identifier ... +and F is a vector of n +or more forms the first n of which match +P_1 through P_n, respectively, and each remaining element of F +matches P_n+1; or + +
  • +P is a datum and F is equal to P in the sense of +the equal? procedure. + +
+ + +

It is an error to use a macro keyword, within the scope of its +binding, in an expression that does not match any of the patterns. +

+

When a macro use is transcribed according to the template of the +matching <syntax rule>, pattern variables that occur in the +template are replaced by the subforms they match in the input. +Pattern variables that occur in subpatterns followed by one or more +instances of the identifier +... are allowed only in subtemplates that are +followed by as many instances of .... +They are replaced in the +output by all of the subforms they match in the input, distributed as +indicated. It is an error if the output cannot be built up as +specified. +

+ +

Identifiers that appear in the template but are not pattern variables +or the identifier +... are inserted into the output as literal identifiers. If a +literal identifier is inserted as a free identifier then it refers to the +binding of that identifier within whose scope the instance of +syntax-rules appears. +If a literal identifier is inserted as a bound identifier then it is +in effect renamed to prevent inadvertent captures of free identifiers. +

+

As an example, if let and cond are defined as in + + +section Derived expression types then they are hygienic (as required) and +the following is not an error. +

+ +
 
(let ((=> #f))
+  (cond (#t => 'ok)))                  ==> ok
+
+ + +

The macro transformer for cond recognizes => +as a local variable, and hence an expression, and not as the +top-level identifier =>, which the macro transformer treats +as a syntactic keyword. Thus the example expands into +

+ +
 
(let ((=> #f))
+  (if #t (begin => 'ok)))
+
+ + +

instead of +

+ +
 
(let ((=> #f))
+  (let ((temp #t))
+    (if temp ('ok temp))))
+
+ + +

which would result in an invalid procedure call. +

+ + + + + +
+ + + + + + + + + + + +
Back: 4.3.2 Pattern languageForward: 5.1 Programs   FastBack: 4. ExpressionsUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: 6. Standard proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

5. Program structure

+ + + + + + + + + +
+ + + + + + + + + + + +
Back: 5. Program structureForward: 5.2 Definitions   FastBack: 5. Program structureUp: 5. Program structureFastForward: 6. Standard proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

5.1 Programs

+ + +

A Scheme program consists of a sequence of expressions, definitions, +and syntax definitions. +Expressions are described in chapter Expressions; +definitions and syntax definitions are the subject of the rest of the +present chapter. +

+

Programs are typically stored in files or entered interactively to a +running Scheme system, although other paradigms are possible; +questions of user interface lie outside the scope of this report. +(Indeed, Scheme would still be useful as a notation for expressing +computational methods even in the absence of a mechanical +implementation.) +

+

Definitions and syntax definitions occurring at the top level of a program +can be interpreted +declaratively. +They cause bindings to be created in the top level +environment or modify the value of existing top-level bindings. +Expressions occurring at the top level of a program are +interpreted imperatively; they are executed in order when the program is +invoked or loaded, and typically perform some kind of initialization. +

+

At the top level of a program (begin <form1> …) is +equivalent to the sequence of expressions, definitions, and syntax definitions +that form the body of the begin. + +

+ + +
+ + + + + + + + + + + +
Back: 5.1 ProgramsForward: 5.2.1 Top level definitions   FastBack: 5. Program structureUp: 5. Program structureFastForward: 6. Standard proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

5.2 Definitions

+ + + + + + + + +

Definitions are valid in some, but not all, contexts where expressions +are allowed. They are valid only at the top level of a <program> +and at the beginning of a <body>. +

+ + +

A definition should have one of the following forms: + +

+ + +
    +
  • (define <variable> <expression>) + +
  • (define (<variable> <formals>) <body>) + +

    <Formals> should be either a +sequence of zero or more variables, or a sequence of one or more +variables followed by a space-delimited period and another variable (as +in a lambda expression). This form is equivalent to +

    +
     
    +(define <variable>
    +  (lambda (<formals>) <body>)).
    +
    + + +
  • (define (<variable> . <formal>) <body>) + +

    <Formal> should be a single +variable. This form is equivalent to +

    +
     
    +(define <variable>
    +  (lambda <formal> <body>)).
    +
    + + + +
+ + +
+ + + + + + + + + + + +
Back: 5.2 DefinitionsForward: 5.2.2 Internal definitions   FastBack: 5. Program structureUp: 5.2 DefinitionsFastForward: 6. Standard proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

5.2.1 Top level definitions

+ + +

At the top level of a program, a definition +

+
 
+(define <variable> <expression>)
+
+ +

has essentially the same effect as the assignment expression +

+
 
+(set! <variable> <expression>)
+
+ +

if <variable> is bound. If <variable> is not bound, +however, then the definition will bind <variable> to a new +location before performing the assignment, whereas it would be an error +to perform a set! on an unbound variable. + +

+ +
 
+(define add3
+  (lambda (x) (+ x 3)))
+(add3 3)                               ==>  6
+(define first car)
+(first '(1 2))                         ==>  1
+
+ + +

Some implementations of Scheme use an initial environment in +which all possible variables are bound to locations, most of +which contain undefined values. Top level definitions in +such an implementation are truly equivalent to assignments. +

+ + + +
+ + + + + + + + + + + +
Back: 5.2.1 Top level definitionsForward: 5.3 Syntax definitions   FastBack: 5. Program structureUp: 5.2 DefinitionsFastForward: 6. Standard proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

5.2.2 Internal definitions

+ + + +

Definitions may occur at the +beginning of a <body> (that is, the body of a lambda, + +let, let*, letrec, let-syntax, or letrec-syntax + + + + + +expression or that of a definition of an appropriate form). +Such definitions are known as internal definitions as opposed to the top level definitions described above. + +The variable defined by an internal definition is local to the +<body>. That is, <variable> is bound rather than assigned, +and the region of the binding is the entire <body>. For example, +

+ +
 
+(let ((x 5))
+  (define foo (lambda (y) (bar x y)))
+  (define bar (lambda (a b) (+ (* a b) a)))
+  (foo (+ x 3)))                       ==>  45
+
+ + +

A <body> containing internal definitions can always be converted +into a completely equivalent letrec expression. For example, the +let expression in the above example is equivalent to +

+ +
 
+(let ((x 5))
+  (letrec ((foo (lambda (y) (bar x y)))
+           (bar (lambda (a b) (+ (* a b) a))))
+    (foo (+ x 3))))
+
+ + +

Just as for the equivalent letrec expression, it must be +possible to evaluate each <expression> of every internal +definition in a <body> without assigning or referring to +the value of any <variable> being defined. +

+

Wherever an internal definition may occur +(begin <definition1> …) +is equivalent to the sequence of definitions +that form the body of the begin. + +

+
+ + + + + + + + + + + +
Back: 5.2.2 Internal definitionsForward: 6. Standard procedures   FastBack: 5. Program structureUp: 5. Program structureFastForward: 6. Standard proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

5.3 Syntax definitions

+ + +

Syntax definitions are valid only at the top level of a <program>. +

+ +

They have the following form: + +

+

(define-syntax <keyword> <transformer spec>) +

+

<Keyword> is an identifier, and +the <transformer spec> should be an instance of syntax-rules. + +The top-level syntactic environment is extended by binding the +<keyword> to the specified transformer. +

+

There is no define-syntax analogue of internal definitions. +

+ + + +

Although macros may expand into definitions and syntax definitions in +any context that permits them, it is an error for a definition or syntax +definition to shadow a syntactic keyword whose meaning is needed to +determine whether some form in the group of forms that contains the +shadowing definition is in fact a definition, or, for internal definitions, +is needed to determine the boundary between the group and the expressions +that follow the group. For example, the following are errors: +

+ +
 
+(define define 3)
+
+(begin (define begin list))
+
+(let-syntax
+  ((foo (syntax-rules ()
+          ((foo (proc args ...) body ...)
+           (define proc
+             (lambda (args ...)
+               body ...))))))
+  (let ((x 3))
+    (foo (plus x y) (+ x y))
+    (define foo x)
+    (plus foo x)))
+
+ + + + + + +
+ + + + + + + + + + + +
Back: 5.3 Syntax definitionsForward: 6.1 Equivalence predicates   FastBack: 5. Program structureUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6. Standard procedures

+ + + + + + + + + + + + + + + + + + + + +

This chapter describes Scheme's built-in procedures. The initial (or +“top level”) Scheme environment starts out with a number of variables +bound to locations containing useful values, most of which are primitive +procedures that manipulate data. For example, the variable abs is +bound to (a location initially containing) a procedure of one argument +that computes the absolute value of a number, and the variable + +is bound to a procedure that computes sums. Built-in procedures that +can easily be written in terms of other built-in procedures are identified as +“library procedures”. +

+

A program may use a top-level definition to bind any variable. It may +subsequently alter any such binding by an assignment (see see section Assignments). +These operations do not modify the behavior of Scheme's built-in +procedures. Altering any top-level binding that has not been introduced by a +definition has an unspecified effect on the behavior of the built-in procedures. +

+
+ + + + + + + + + + + +
Back: 6. Standard proceduresForward: 6.2 Numbers   FastBack: 6. Standard proceduresUp: 6. Standard proceduresFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.1 Equivalence predicates

+ + + +

A predicate is a procedure that always returns a boolean + +value (#t or #f). An equivalence predicate is + +the computational analogue of a mathematical equivalence relation (it is +symmetric, reflexive, and transitive). Of the equivalence predicates +described in this section, eq? is the finest or most +discriminating, and equal? is the coarsest. Eqv? is +slightly less discriminating than eq?. +

+ + + +
(eqv? obj1 obj2)procedure
+ +

The eqv? procedure defines a useful equivalence relation on objects. +Briefly, it returns #t if obj1 and obj2 should +normally be regarded as the same object. This relation is left slightly +open to interpretation, but the following partial specification of +eqv? holds for all implementations of Scheme. +

+

The eqv? procedure returns #t if: +

+ + +
    +
  • +obj1 and obj2 are both #t or both #f. + +
  • +obj1 and obj2 are both symbols and + + +
     
    (string=? (symbol->string obj1)
    +          (symbol->string obj2))
    +                                  ==>  #t
    +
    + + + +

    Note: +This assumes that neither obj1 nor obj2 is an “uninterned +symbol” as alluded to in section Symbols. This report does +not presume to specify the behavior of eqv? on implementation-dependent +extensions. +

    + + +
  • +obj1 and obj2 are both numbers, are numerically +equal (see =, section see section Numbers), and are either both +exact or both inexact. + +
  • +obj1 and obj2 are both characters and are the same +character according to the char=? procedure +(section see section Characters). + +
  • +both obj1 and obj2 are the empty list. + +
  • +obj1 and obj2 are pairs, vectors, or strings that denote the +same locations in the store (section see section Storage model). + +
  • +obj1 and obj2 are procedures whose location tags are +equal (section see section Procedures). + +
+ + + + +

The eqv? procedure returns #f if: +

+ + +
    +
  • +obj1 and obj2 are of different types +(section see section Disjointness of types). + +
  • +one of obj1 and obj2 is #t but the other is +#f. + +
  • +obj1 and obj2 are symbols but + + +
     
    (string=? (symbol->string obj1)
    +          (symbol->string obj2))
    +                                  ==>  #f
    +
    + + +
  • +one of obj1 and obj2 is an exact number but the other +is an inexact number. + +
  • +obj1 and obj2 are numbers for which the = +procedure returns #f. + +
  • +obj1 and obj2 are characters for which the char=? +procedure returns #f. + +
  • +one of obj1 and obj2 is the empty list but the other +is not. + +
  • +obj1 and obj2 are pairs, vectors, or strings that denote +distinct locations. + +
  • +obj1 and obj2 are procedures that would behave differently +(return different value(s) or have different side effects) for some arguments. + + +
+ + + +
 
(eqv? 'a 'a)                           ==>  #t
+(eqv? 'a 'b)                           ==>  #f
+(eqv? 2 2)                             ==>  #t
+(eqv? '() '())                         ==>  #t
+(eqv? 100000000 100000000)             ==>  #t
+(eqv? (cons 1 2) (cons 1 2))           ==>  #f
+(eqv? (lambda () 1)
+      (lambda () 2))                   ==>  #f
+(eqv? #f 'nil)                         ==>  #f
+(let ((p (lambda (x) x)))
+  (eqv? p p))                          ==>  #t
+
+ + +

The following examples illustrate cases in which the above rules do +not fully specify the behavior of eqv?. All that can be said +about such cases is that the value returned by eqv? must be a +boolean. +

+ +
 
(eqv? "" "")                           ==>  unspecified
+(eqv? '#() '#())                       ==>  unspecified
+(eqv? (lambda (x) x)
+      (lambda (x) x))                  ==>  unspecified
+(eqv? (lambda (x) x)
+      (lambda (y) y))                  ==>  unspecified
+
+ + +

The next set of examples shows the use of eqv? with procedures +that have local state. Gen-counter must return a distinct +procedure every time, since each procedure has its own internal counter. +Gen-loser, however, returns equivalent procedures each time, since +the local state does not affect the value or side effects of the +procedures. +

+ +
 
(define gen-counter
+  (lambda ()
+    (let ((n 0))
+      (lambda () (set! n (+ n 1)) n))))
+(let ((g (gen-counter)))
+  (eqv? g g))                          ==>  #t
+(eqv? (gen-counter) (gen-counter))
+                                       ==>  #f
+(define gen-loser
+  (lambda ()
+    (let ((n 0))
+      (lambda () (set! n (+ n 1)) 27))))
+(let ((g (gen-loser)))
+  (eqv? g g))                          ==>  #t
+(eqv? (gen-loser) (gen-loser))
+                                       ==>  unspecified
+
+(letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
+         (g (lambda () (if (eqv? f g) 'both 'g))))
+  (eqv? f g))
+                                       ==>  unspecified
+
+(letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
+         (g (lambda () (if (eqv? f g) 'g 'both))))
+  (eqv? f g))
+                                       ==>  #f
+
+ + + + +

Since it is an error to modify constant objects (those returned by +literal expressions), implementations are permitted, though not +required, to share structure between constants where appropriate. Thus +the value of eqv? on constants is sometimes +implementation-dependent. +

+ +
 
(eqv? '(a) '(a))                       ==>  unspecified
+(eqv? "a" "a")                         ==>  unspecified
+(eqv? '(b) (cdr '(a b)))               ==>  unspecified
+(let ((x '(a)))
+  (eqv? x x))                          ==>  #t
+
+ + + +

Rationale: +The above definition of eqv? allows implementations latitude in +their treatment of procedures and literals: implementations are free +either to detect or to fail to detect that two procedures or two literals +are equivalent to each other, and can decide whether or not to +merge representations of equivalent objects by using the same pointer or +bit pattern to represent both. +

+ + + + + + +
(eq? obj1 obj2)procedure
+ +

Eq? is similar to eqv? except that in some cases it is +capable of discerning distinctions finer than those detectable by +eqv?. +

+

Eq? and eqv? are guaranteed to have the same +behavior on symbols, booleans, the empty list, pairs, procedures, +and non-empty +strings and vectors. Eq?'s behavior on numbers and characters is +implementation-dependent, but it will always return either true or +false, and will return true only when eqv? would also return +true. Eq? may also behave differently from eqv? on empty +vectors and empty strings. +

+ +
 
(eq? 'a 'a)                            ==>  #t
+(eq? '(a) '(a))                        ==>  unspecified
+(eq? (list 'a) (list 'a))              ==>  #f
+(eq? "a" "a")                          ==>  unspecified
+(eq? "" "")                            ==>  unspecified
+(eq? '() '())                          ==>  #t
+(eq? 2 2)                              ==>  unspecified
+(eq? #\A #\A)                          ==>  unspecified
+(eq? car car)                          ==>  #t
+(let ((n (+ 2 3)))
+  (eq? n n))                           ==>  unspecified
+(let ((x '(a)))
+  (eq? x x))                           ==>  #t
+(let ((x '#()))
+  (eq? x x))                           ==>  #t
+(let ((p (lambda (x) x)))
+  (eq? p p))                           ==>  #t
+
+ + + + + +

Rationale: It will usually be possible to implement eq? much +more efficiently than eqv?, for example, as a simple pointer +comparison instead of as some more complicated operation. One reason is +that it may not be possible to compute eqv? of two numbers in +constant time, whereas eq? implemented as pointer comparison will +always finish in constant time. Eq? may be used like eqv? +in applications using procedures to implement objects with state since +it obeys the same constraints as eqv?. +

+ + + + + + +
(equal? obj1 obj2)library procedure
+ +

Equal? recursively compares the contents of pairs, vectors, and +strings, applying eqv? on other objects such as numbers and symbols. +A rule of thumb is that objects are generally equal? if they print +the same. Equal? may fail to terminate if its arguments are +circular data structures. +

+ +
 
(equal? 'a 'a)                         ==>  #t
+(equal? '(a) '(a))                     ==>  #t
+(equal? '(a (b) c)
+        '(a (b) c))                    ==>  #t
+(equal? "abc" "abc")                   ==>  #t
+(equal? 2 2)                           ==>  #t
+(equal? (make-vector 5 'a)
+        (make-vector 5 'a))            ==>  #t
+(equal? (lambda (x) x)
+        (lambda (y) y))                ==>  unspecified
+
+ + + + + +
+ + + + + + + + + + + +
Back: 6.1 Equivalence predicatesForward: 6.2.1 Numerical types   FastBack: 6. Standard proceduresUp: 6. Standard proceduresFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.2 Numbers

+ + + + + + + + + + + + + + + + +

Numerical computation has traditionally been neglected by the Lisp +community. Until Common Lisp there was no carefully thought out +strategy for organizing numerical computation, and with the exception of +the MacLisp system [Pitman83] little effort was made to +execute numerical code efficiently. This report recognizes the excellent work +of the Common Lisp committee and accepts many of their recommendations. +In some ways this report simplifies and generalizes their proposals in a manner +consistent with the purposes of Scheme. +

+

It is important to distinguish between the mathematical numbers, the +Scheme numbers that attempt to model them, the machine representations +used to implement the Scheme numbers, and notations used to write numbers. +This report uses the types number, complex, real, +rational, and integer to refer to both mathematical numbers +and Scheme numbers. Machine representations such as fixed point and +floating point are referred to by names such as fixnum and +flonum. +

+ +
+ + + + + + + + + + + +
Back: 6.2 NumbersForward: 6.2.2 Exactness   FastBack: 6. Standard proceduresUp: 6.2 NumbersFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.2.1 Numerical types

+ + + + + + + +

Mathematically, numbers may be arranged into a tower of subtypes +in which each level is a subset of the level above it: +

+
 
         number 
+          complex 
+          real 
+          rational 
+          integer 
+
+ + +

For example, 3 is an integer. Therefore 3 is also a rational, +a real, and a complex. The same is true of the Scheme numbers +that model 3. For Scheme numbers, these types are defined by the +predicates number?, complex?, real?, rational?, + + + + +and integer?. + +

+

There is no simple relationship between a number's type and its +representation inside a computer. Although most implementations of +Scheme will offer at least two different representations of 3, these +different representations denote the same integer. +

+ +

Scheme's numerical operations treat numbers as abstract data, as +independent of their representation as possible. Although an implementation +of Scheme may use fixnum, flonum, and perhaps other representations for +numbers, this should not be apparent to a casual programmer writing +simple programs. +

+

It is necessary, however, to distinguish between numbers that are +represented exactly and those that may not be. For example, indexes +into data structures must be known exactly, as must some polynomial +coefficients in a symbolic algebra system. On the other hand, the +results of measurements are inherently inexact, and irrational numbers +may be approximated by rational and therefore inexact approximations. +In order to catch uses of inexact numbers where exact numbers are +required, Scheme explicitly distinguishes exact from inexact numbers. +This distinction is orthogonal to the dimension of type. +

+
+ + + + + + + + + + + +
Back: 6.2.1 Numerical typesForward: 6.2.3 Implementation restrictions   FastBack: 6. Standard proceduresUp: 6.2 NumbersFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.2.2 Exactness

+ + + + + +

Scheme numbers are either exact or inexact. A number is +exact if it was written as an exact constant or was derived from +exact numbers using only exact operations. A number is +inexact if it was written as an inexact constant, +if it was +derived using inexact ingredients, or if it was derived using +inexact operations. Thus inexactness is a contagious +property of a number. +

+

If two implementations produce exact results for a +computation that did not involve inexact intermediate results, +the two ultimate results will be mathematically equivalent. This is +generally not true of computations involving inexact numbers +since approximate methods such as floating point arithmetic may be used, +but it is the duty of each implementation to make the result as close as +practical to the mathematically ideal result. +

+

Rational operations such as + should always produce +exact results when given exact arguments. +If the operation is unable to produce an exact result, +then it may either report the violation of an implementation restriction +or it may silently coerce its +result to an inexact value. +See section Implementation restrictions. +

+

With the exception of inexact->exact, the operations described in + +this section must generally return inexact results when given any inexact +arguments. An operation may, however, return an exact result if it can +prove that the value of the result is unaffected by the inexactness of its +arguments. For example, multiplication of any number by an exact zero +may produce an exact zero result, even if the other argument is +inexact. +

+
+ + + + + + + + + + + +
Back: 6.2.2 ExactnessForward: 6.2.4 Syntax of numerical constants   FastBack: 6. Standard proceduresUp: 6.2 NumbersFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.2.3 Implementation restrictions

+ + + + + +

Implementations of Scheme are not required to implement the whole +tower of subtypes given in section Numerical types, +but they must implement a coherent subset consistent with both the +purposes of the implementation and the spirit of the Scheme language. +For example, an implementation in which all numbers are real +may still be quite useful. +

+

Implementations may also support only a limited range of numbers of +any type, subject to the requirements of this section. The supported +range for exact numbers of any type may be different from the +supported range for inexact numbers of that type. For example, +an implementation that uses flonums to represent all its +inexact real numbers may +support a practically unbounded range of exact integers +and rationals +while limiting the range of inexact reals (and therefore +the range of inexact integers and rationals) +to the dynamic range of the flonum format. +Furthermore +the gaps between the representable inexact integers and +rationals are +likely to be very large in such an implementation as the limits of this +range are approached. +

+

An implementation of Scheme must support exact integers +throughout the range of numbers that may be used for indexes of +lists, vectors, and strings or that may result from computing the length of a +list, vector, or string. The length, vector-length, + + +and string-length procedures must return an exact + +integer, and it is an error to use anything but an exact integer as an +index. Furthermore any integer constant within the index range, if +expressed by an exact integer syntax, will indeed be read as an exact +integer, regardless of any implementation restrictions that may apply +outside this range. Finally, the procedures listed below will always +return an exact integer result provided all their arguments are exact integers +and the mathematically expected result is representable as an exact integer +within the implementation: +

+ +
 
++            -             *
+quotient     remainder     modulo
+max          min           abs
+numerator    denominator   gcd
+lcm          floor         ceiling
+truncate     round         rationalize
+expt
+
+ + +

Implementations are encouraged, but not required, to support +exact integers and exact rationals of +practically unlimited size and precision, and to implement the +above procedures and the / procedure in +such a way that they always return exact results when given exact +arguments. If one of these procedures is unable to deliver an exact +result when given exact arguments, then it may either report a +violation of an +implementation restriction or it may silently coerce its result to an +inexact number. Such a coercion may cause an error later. +

+ + +

An implementation may use floating point and other approximate +representation strategies for inexact numbers. +

+ +

This report recommends, but does not require, that the IEEE 32-bit +and 64-bit floating point standards be followed by implementations that use +flonum representations, and that implementations using +other representations should match or exceed the precision achievable +using these floating point standards [IEEE]. +

+

In particular, implementations that use flonum representations +must follow these rules: A flonum result +must be represented with at least as much precision as is used to express any of +the inexact arguments to that operation. It is desirable (but not required) for +potentially inexact operations such as sqrt, when applied to exact +arguments, to produce exact answers whenever possible (for example the +square root of an exact 4 ought to be an exact 2). +If, however, an +exact number is operated upon so as to produce an inexact result +(as by sqrt), and if the result is represented as a flonum, then +the most precise flonum format available must be used; but if the result +is represented in some other way then the representation must have at least as +much precision as the most precise flonum format available. +

+

Although Scheme allows a variety of written +notations for +numbers, any particular implementation may support only some of them. +For example, an implementation in which all numbers are real +need not support the rectangular and polar notations for complex +numbers. If an implementation encounters an exact numerical constant that +it cannot represent as an exact number, then it may either report a +violation of an implementation restriction or it may silently represent the +constant by an inexact number. +

+ +
+ + + + + + + + + + + +
Back: 6.2.3 Implementation restrictionsForward: 6.2.5 Numerical operations   FastBack: 6. Standard proceduresUp: 6.2 NumbersFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.2.4 Syntax of numerical constants

+ + + + + + +

The syntax of the written representations for numbers is described formally in +section Lexical structure. Note that case is not significant in numerical +constants. +

+ +

A number may be written in binary, octal, decimal, or +hexadecimal by the use of a radix prefix. The radix prefixes are #b (binary), #o (octal), #d (decimal), and #x (hexadecimal). With + + + + +no radix prefix, a number is assumed to be expressed in decimal. +

+

A +numerical constant may be specified to be either exact or +inexact by a prefix. The prefixes are #e + +for exact, and #i for inexact. An exactness + +prefix may appear before or after any radix prefix that is used. If +the written representation of a number has no exactness prefix, the +constant may be either inexact or exact. It is +inexact if it contains a decimal point, an +exponent, or a “#” character in the place of a digit, +otherwise it is exact. +

+ +

In systems with inexact numbers +of varying precisions it may be useful to specify +the precision of a constant. For this purpose, numerical constants +may be written with an exponent marker that indicates the +desired precision of the inexact +representation. The letters s, f, +d, and l specify the use of short, single, +double, and long precision, respectively. (When fewer +than four internal +inexact +representations exist, the four size +specifications are mapped onto those available. For example, an +implementation with two internal representations may map short and +single together and long and double together.) In addition, the +exponent marker e specifies the default precision for the +implementation. The default precision has at least as much precision +as double, but +implementations may wish to allow this default to be set by the user. +

+ +
 
+3.14159265358979F0
+       Round to single --- 3.141593
+0.6L0
+       Extend to long --- .600000000000000
+
+ + + +
+ + + + + + + + + + + +
Back: 6.2.4 Syntax of numerical constantsForward: 6.2.6 Numerical input and output   FastBack: 6. Standard proceduresUp: 6.2 NumbersFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.2.5 Numerical operations

+ + +

The reader is referred to section Entry format for a summary +of the naming conventions used to specify restrictions on the types of +arguments to numerical routines. +

+

The examples used in this section assume that any numerical constant written +using an exact notation is indeed represented as an exact +number. Some examples also assume that certain numerical constants written +using an inexact notation can be represented without loss of +accuracy; the inexact constants were chosen so that this is +likely to be true in implementations that use flonums to represent +inexact numbers. +

+ + + +
(number? obj)procedure
+
(complex? obj)procedure
+
(real? obj)procedure
+
(rational? obj)procedure
+
(integer? obj)procedure
+ +

These numerical type predicates can be applied to any kind of +argument, including non-numbers. They return #t if the object is +of the named type, and otherwise they return #f. +In general, if a type predicate is true of a number then all higher +type predicates are also true of that number. Consequently, if a type +predicate is false of a number, then all lower type predicates are +also false of that number. +

+

If z is an inexact complex number, then (real? z) is true if +and only if (zero? (imag-part z)) is true. If x is an inexact +real number, then (integer? x) is true if and only if +(= x (round x)). +

+ +
 
(complex? 3+4i)                        ==>  #t
+(complex? 3)                           ==>  #t
+(real? 3)                              ==>  #t
+(real? -2.5+0.0i)                      ==>  #t
+(real? #e1e10)                         ==>  #t
+(rational? 6/10)                       ==>  #t
+(rational? 6/3)                        ==>  #t
+(integer? 3+0i)                        ==>  #t
+(integer? 3.0)                         ==>  #t
+(integer? 8/4)                         ==>  #t
+
+ + + +

Note: +The behavior of these type predicates on inexact numbers +is unreliable, since any inaccuracy may affect the result. +

+ + + +

Note: +In many implementations the rational? procedure will be the same + +as real?, and the complex? procedure will be the same as + + +number?, but unusual implementations may be able to represent + +some irrational numbers exactly or may extend the number system to +support some kind of non-complex numbers. +

+ + + + + +
(exact? z)procedure
+
(inexact? z)procedure
+ +

These numerical predicates provide tests for the exactness of a +quantity. For any Scheme number, precisely one of these predicates +is true. +

+ + + + +
(= z1 z2 z3 …)procedure
+
(< x1 x2 x3 …)procedure
+
(> x1 x2 x3 …)procedure
+
(<= x1 x2 x3 …)procedure
+
(>= x1 x2 x3 …)procedure
+ +

These procedures return #t if their arguments are (respectively): +equal, monotonically increasing, monotonically decreasing, +monotonically nondecreasing, or monotonically nonincreasing. +

+

These predicates are required to be transitive. +

+ +

Note: +The traditional implementations of these predicates in Lisp-like +languages are not transitive. +

+ + + +

Note: +While it is not an error to compare inexact numbers using these +predicates, the results may be unreliable because a small inaccuracy +may affect the result; this is especially true of = and zero?. + + +When in doubt, consult a numerical analyst. +

+ + + + + +
(zero? z)library procedure
+
(positive? x)library procedure
+
(negative? x)library procedure
+
(odd? n)library procedure
+
(even? n)library procedure
+ +

These numerical predicates test a number for a particular property, +returning #t or #f. See note above. +

+ + + +
(max x1 x2 …)library procedure
+
(min x1 x2 …)library procedure
+ +

These procedures return the maximum or minimum of their arguments. +

+ +
 
(max 3 4)                              ==>  4    ; exact
+(max 3.9 4)                            ==>  4.0  ; inexact
+
+ + + +

Note: +If any argument is inexact, then the result will also be inexact (unless +the procedure can prove that the inaccuracy is not large enough to affect the +result, which is possible only in unusual implementations). If min or +max is used to compare numbers of mixed exactness, and the numerical +value of the result cannot be represented as an inexact number without loss of +accuracy, then the procedure may report a violation of an implementation +restriction. +

+ + + + + + +
(+ z1 …)procedure
+
(* z1 …)procedure
+ +

These procedures return the sum or product of their arguments. +

+ +
 
(+ 3 4)                                ==>  7
+(+ 3)                                  ==>  3
+(+)                                    ==>  0
+(* 4)                                  ==>  4
+(*)                                    ==>  1
+
+ + + + + + +
(- z1 z2)procedure
+
(- z)procedure
+
(- z1 z2 …)optional procedure
+
(/ z1 z2)procedure
+
(/ z)procedure
+
(/ z1 z2 …)optional procedure
+ +

With two or more arguments, these procedures return the difference or +quotient of their arguments, associating to the left. With one argument, +however, they return the additive or multiplicative inverse of their argument. +

+ +
 
(- 3 4)                                ==>  -1
+(- 3 4 5)                              ==>  -6
+(- 3)                                  ==>  -3
+(/ 3 4 5)                              ==>  3/20
+(/ 3)                                  ==>  1/3
+
+ + + + + + +
(abs x)library procedure
+ +

Abs returns the absolute value of its argument. +

+
 
(abs -7)                               ==>  7
+
+ + + + + +
(quotient n1 n2)procedure
+
(remainder n1 n2)procedure
+
(modulo n1 n2)procedure
+ +

These procedures implement number-theoretic (integer) +division. n2 should be non-zero. All three procedures +return integers. If n1/n2 is an integer: +

+
 
    (quotient n1 n2)                   ==> n1/n2
+    (remainder n1 n2)                  ==> 0
+    (modulo n1 n2)                     ==> 0
+
+ +

If n1/n2 is not an integer: +

+
 
    (quotient n1 n2)                   ==> n_q
+    (remainder n1 n2)                  ==> n_r
+    (modulo n1 n2)                     ==> n_m
+
+ +

where n_q is n1/n2 rounded towards zero, +0 < |n_r| < |n2|, 0 < |n_m| < |n2|, +n_r and n_m differ from n1 by a multiple of n2, +n_r has the same sign as n1, and +n_m has the same sign as n2. +

+

From this we can conclude that for integers n1 and n2 with +n2 not equal to 0, +

+
 
     (= n1 (+ (* n2 (quotient n1 n2))
+           (remainder n1 n2)))
+                                       ==>  #t
+
+ +

provided all numbers involved in that computation are exact. +

+ +
 
(modulo 13 4)                          ==>  1
+(remainder 13 4)                       ==>  1
+
+(modulo -13 4)                         ==>  3
+(remainder -13 4)                      ==>  -1
+
+(modulo 13 -4)                         ==>  -3
+(remainder 13 -4)                      ==>  1
+
+(modulo -13 -4)                        ==>  -1
+(remainder -13 -4)                     ==>  -1
+
+(remainder -13 -4.0)                   ==>  -1.0  ; inexact
+
+ + + + +
(gcd n1 …)library procedure
+
(lcm n1 …)library procedure
+ +

These procedures return the greatest common divisor or least common +multiple of their arguments. The result is always non-negative. +

+ +
 
(gcd 32 -36)                           ==>  4
+(gcd)                                  ==>  0
+(lcm 32 -36)                           ==>  288
+(lcm 32.0 -36)                         ==>  288.0  ; inexact
+(lcm)                                  ==>  1
+
+ + + + + + +
(numerator q)procedure
+
(denominator q)procedure
+ +

These procedures return the numerator or denominator of their +argument; the result is computed as if the argument was represented as +a fraction in lowest terms. The denominator is always positive. The +denominator of 0 is defined to be 1. +

+ + +
 
(numerator (/ 6 4))                    ==>  3
+(denominator (/ 6 4))                  ==>  2
+(denominator
+  (exact->inexact (/ 6 4)))            ==> 2.0
+
+ + + + + + +
(floor x)procedure
+
(ceiling x)procedure
+
(truncate x)procedure
+
(round x)procedure
+ + +

These procedures return integers. +Floor returns the largest integer not larger than x. +Ceiling returns the smallest integer not smaller than x. +Truncate returns the integer closest to x whose absolute +value is not larger than the absolute value of x. Round returns the +closest integer to x, rounding to even when x is halfway between two +integers. +

+ +

Rationale: +Round rounds to even for consistency with the default rounding +mode specified by the IEEE floating point standard. +

+ + + +

Note: +If the argument to one of these procedures is inexact, then the result +will also be inexact. If an exact value is needed, the +result should be passed to the inexact->exact procedure. +

+ + + +
 
(floor -4.3)                           ==>  -5.0
+(ceiling -4.3)                         ==>  -4.0
+(truncate -4.3)                        ==>  -4.0
+(round -4.3)                           ==>  -4.0
+
+(floor 3.5)                            ==>  3.0
+(ceiling 3.5)                          ==>  4.0
+(truncate 3.5)                         ==>  3.0
+(round 3.5)                            ==>  4.0  ; inexact
+
+(round 7/2)                            ==>  4    ; exact
+(round 7)                              ==>  7
+
+ + + + + +
(rationalize x y)library procedure
+ + +

Rationalize returns the simplest rational number +differing from x by no more than y. A rational number r_1 is +simpler than another rational number + +r_2 if r_1 = p_1/q_1 and r_2 = p_2/q_2 (in lowest terms) and |p_1|<= |p_2| and |q_1| <= |q_2|. Thus 3/5 is simpler than 4/7. +Although not all rationals are comparable in this ordering (consider 2/7 +and 3/5) any interval contains a rational number that is simpler than +every other rational number in that interval (the simpler 2/5 lies +between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of +all. +

+ +
 
(rationalize
+  (inexact->exact .3) 1/10)            ==> 1/3    ; exact
+(rationalize .3 1/10)                  ==> #i1/3  ; inexact
+
+ + + + + +
(exp z)procedure
+
(log z)procedure
+
(sin z)procedure
+
(cos z)procedure
+
(tan z)procedure
+
(asin z)procedure
+
(acos z)procedure
+
(atan z)procedure
+
(atan y x)procedure
+ +

These procedures are part of every implementation that supports +general +real numbers; they compute the usual transcendental functions. log +computes the natural logarithm of z (not the base ten logarithm). +asin, acos, and atan compute arcsine (sin^-1), +arccosine (cos^-1), and arctangent (tan^-1), respectively. +The two-argument variant of atan computes (angle +(make-rectangular x y)) (see below), even in implementations +that don't support general complex numbers. +

+

In general, the mathematical functions log, arcsine, arccosine, and +arctangent are multiply defined. +The value of log z is defined to be the one whose imaginary +part lies in the range from -pi (exclusive) to pi (inclusive). +log 0 is undefined. +With log defined this way, the values of sin^-1 z, cos^-1 z, +and tan^-1 z are according to the following formulae: +

+ +

sin^-1 z = -i log (i z + sqrt(1 - z^2)) +

+ + +

cos^-1 z = pi / 2 - sin^-1 z +

+ + +

tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i) +

+ +

The above specification follows [CLtL], which in turn +cites [Penfield81]; refer to these sources for more detailed +discussion of branch cuts, boundary conditions, and implementation of +these functions. When it is possible these procedures produce a real +result from a real argument. +

+ + + + + + + +
(sqrt z)procedure
+ +

Returns the principal square root of z. The result will have +either positive real part, or zero real part and non-negative imaginary +part. +

+ + + +
(expt z1 z2)procedure
+ +

Returns z1 raised to the power z2. For z_1 ~= 0 +

+ +

z_1^z_2 = e^z_2 log z_1 +

+

0^z is 1 if z = 0 and 0 otherwise. +

+ + + + + +
(make-rectangular x1 x2)procedure
+
(make-polar x3 x4)procedure
+
(real-part z)procedure
+
(imag-part z)procedure
+
(magnitude z)procedure
+
(angle z)procedure
+ +

These procedures are part of every implementation that supports +general +complex numbers. Suppose x1, x2, x3, and x4 are +real numbers and z is a complex number such that +

+ +

z = x1 + x2i = x3 . e^i x4 +

+

Then +

+
 
(make-rectangular x1 x2)               ==> z
+(make-polar x3 x4)                     ==> z
+(real-part z)                          ==> x1
+(imag-part z)                          ==> x2
+(magnitude z)                          ==> |x3|
+(angle z)                              ==> x_angle
+
+ +

where -pi < x_angle <= pi with x_angle = x4 + 2pi n +for some integer n. +

+ +

Rationale: +Magnitude is the same as abs for a real argument, + +but abs must be present in all implementations, whereas +magnitude need only be present in implementations that support +general complex numbers. +

+ + + + + + +
(exact->inexact z)procedure
+
(inexact->exact z)procedure
+ +

Exact->inexact returns an inexact representation of z. +The value returned is the +inexact number that is numerically closest to the argument. +If an exact argument has no reasonably close inexact equivalent, +then a violation of an implementation restriction may be reported. +

+

Inexact->exact returns an exact representation of +z. The value returned is the exact number that is numerically +closest to the argument. +If an inexact argument has no reasonably close exact equivalent, +then a violation of an implementation restriction may be reported. +

+ +

These procedures implement the natural one-to-one correspondence between +exact and inexact integers throughout an +implementation-dependent range. See section Implementation restrictions. +

+ + +
+
+
+ +
+ + + + + + + + + + + +
Back: 6.2.5 Numerical operationsForward: 6.3 Other data types   FastBack: 6. Standard proceduresUp: 6.2 NumbersFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.2.6 Numerical input and output

+ + + +
(number->string z)procedure
+
(number->string z radix)procedure
+ +

Radix must be an exact integer, either 2, 8, 10, or 16. If omitted, +radix defaults to 10. +The procedure number->string takes a +number and a radix and returns as a string an external representation of +the given number in the given radix such that +

+
 
(let ((number number)
+      (radix radix))
+  (eqv? number
+        (string->number (number->string number
+                                        radix)
+                        radix)))
+
+ +

is true. It is an error if no possible result makes this expression true. +

+

If z is inexact, the radix is 10, and the above expression +can be satisfied by a result that contains a decimal point, +then the result contains a decimal point and is expressed using the +minimum number of digits (exclusive of exponent and trailing +zeroes) needed to make the above expression +true [howtoprint], [howtoread]; +otherwise the format of the result is unspecified. +

+

The result returned by number->string +never contains an explicit radix prefix. +

+ +

Note: +The error case can occur only when z is not a complex number +or is a complex number with a non-rational real or imaginary part. +

+ + + +

Rationale: +If z is an inexact number represented using flonums, and +the radix is 10, then the above expression is normally satisfied by +a result containing a decimal point. The unspecified case +allows for infinities, NaNs, and non-flonum representations. +

+ + + + + + +
(string->number string)procedure
+
(string->number string radix)procedure
+ + +

Returns a number of the maximally precise representation expressed by the +given string. Radix must be an exact integer, either 2, 8, 10, +or 16. If supplied, radix is a default radix that may be overridden +by an explicit radix prefix in string (e.g. "#o177"). If radix +is not supplied, then the default radix is 10. If string is not +a syntactically valid notation for a number, then string->number +returns #f. +

+ +
 
(string->number "100")                 ==>  100
+(string->number "100" 16)              ==>  256
+(string->number "1e2")                 ==>  100.0
+(string->number "15##")                ==>  1500.0
+
+ + + +

Note: +The domain of string->number may be restricted by implementations +in the following ways. String->number is permitted to return +#f whenever string contains an explicit radix prefix. +If all numbers supported by an implementation are real, then +string->number is permitted to return #f whenever +string uses the polar or rectangular notations for complex +numbers. If all numbers are integers, then +string->number may return #f whenever +the fractional notation is used. If all numbers are exact, then +string->number may return #f whenever +an exponent marker or explicit exactness prefix is used, or if +a # appears in place of a digit. If all inexact +numbers are integers, then +string->number may return #f whenever +a decimal point is used. +

+ + + + +
+ + + + + + + + + + + +
Back: 6.2.6 Numerical input and outputForward: 6.3.1 Booleans   FastBack: 6. Standard proceduresUp: 6. Standard proceduresFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.3 Other data types

+ + + + + + + + + + + +

This section describes operations on some of Scheme's non-numeric data types: +booleans, pairs, lists, symbols, characters, strings and vectors. +

+
+ + + + + + + + + + + +
Back: 6.3 Other data typesForward: 6.3.2 Pairs and lists   FastBack: 6. Standard proceduresUp: 6.3 Other data typesFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.3.1 Booleans

+ + + +

The standard boolean objects for true and false are written as +#t and #f. What really + + +matters, though, are the objects that the Scheme conditional expressions +(if, cond, and, or, do) treat as +true or false. The phrase “a true value” + + +(or sometimes just “true”) means any object treated as true by the +conditional expressions, and the phrase “a false value” (or + +“false”) means any object treated as false by the conditional expressions. +

+

Of all the standard Scheme values, only #f +counts as false in conditional expressions. +Except for #f, +all standard Scheme values, including #t, +pairs, the empty list, symbols, numbers, strings, vectors, and procedures, +count as true. +

+ + + +

Note: +Programmers accustomed to other dialects of Lisp should be aware that +Scheme distinguishes both #f and the empty list + +from the symbol nil. + +

+ + +

Boolean constants evaluate to themselves, so they do not need to be quoted +in programs. +

+ +
 
+#t                                     ==>  #t
+#f                                     ==>  #f
+'#f                                    ==>  #f
+
+ + + + +
(not obj)library procedure
+ +

Not returns #t if obj is false, and returns +#f otherwise. +

+ +
 
(not #t)                               ==>  #f
+(not 3)                                ==>  #f
+(not (list 3))                         ==>  #f
+(not #f)                               ==>  #t
+(not '())                              ==>  #f
+(not (list))                           ==>  #f
+(not 'nil)                             ==>  #f
+
+ + + + + + +
(boolean? obj)library procedure
+ +

Boolean? returns #t if obj is either #t or +#f and returns #f otherwise. +

+ +
 
(boolean? #f)                          ==>  #t
+(boolean? 0)                           ==>  #f
+(boolean? '())                         ==>  #f
+
+ + + + + +
+ + + + + + + + + + + +
Back: 6.3.1 BooleansForward: 6.3.3 Symbols   FastBack: 6. Standard proceduresUp: 6.3 Other data typesFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.3.2 Pairs and lists

+ + + +

A pair (sometimes called a dotted pair) is a + + +record structure with two fields called the car and cdr fields (for +historical reasons). Pairs are created by the procedure cons. +The car and cdr fields are accessed by the procedures car and +cdr. The car and cdr fields are assigned by the procedures +set-car! and set-cdr!. +

+

Pairs are used primarily to represent lists. A list can +be defined recursively as either the empty list or a pair whose + +cdr is a list. More precisely, the set of lists is defined as the smallest +set X such that +

+ + +
    +
  • +The empty list is in X. +
  • +If list is in X, then any pair whose cdr field contains +list is also in X. + +
+ + +

The objects in the car fields of successive pairs of a list are the +elements of the list. For example, a two-element list is a pair whose car +is the first element and whose cdr is a pair whose car is the second element +and whose cdr is the empty list. The length of a list is the number of +elements, which is the same as the number of pairs. +

+

The empty list is a special object of its own type + +(it is not a pair); it has no elements and its length is zero. +

+ +

Note: +The above definitions imply that all lists have finite length and are +terminated by the empty list. +

+ + +

The most general notation (external representation) for Scheme pairs is +the “dotted” notation (c1 . c2) where +c1 is the value of the car field and c2 is the value of the +cdr field. For example (4 . 5) is a pair whose car is 4 and whose +cdr is 5. Note that (4 . 5) is the external representation of a +pair, not an expression that evaluates to a pair. +

+

A more streamlined notation can be used for lists: the elements of the +list are simply enclosed in parentheses and separated by spaces. The +empty list is written () . For example, + +

+ +
 
+(a b c d e)
+
+ + +

and +

+ +
 
+(a . (b . (c . (d . (e . ())))))
+
+ + +

are equivalent notations for a list of symbols. +

+

A chain of pairs not ending in the empty list is called an +improper list. Note that an improper list is not a list. + +The list and dotted notations can be combined to represent +improper lists: +

+ +
 
+(a b c . d)
+
+ + +

is equivalent to +

+ +
 
+(a . (b . (c . d)))
+
+ + +

Whether a given pair is a list depends upon what is stored in the cdr +field. When the set-cdr! procedure is used, an object can be a + +list one moment and not the next: +

+ +
 
+(define x (list 'a 'b 'c))
+(define y x)
+y                                      ==>  (a b c)
+(list? y)                              ==>  #t
+(set-cdr! x 4)                         ==>  unspecified
+x                                      ==>  (a . 4)
+(eqv? x y)                             ==>  #t
+y                                      ==>  (a . 4)
+(list? y)                              ==>  #f
+(set-cdr! x x)                         ==>  unspecified
+(list? x)                              ==>  #f
+
+ + + + +

Within literal expressions and representations of objects read by the +read procedure, the forms '<datum>, + + +<datum>, ,<datum>, and + +,@<datum> denote two-element lists whose first elements are +the symbols quote, quasiquote, unquote, and + + + +unquote-splicing, respectively. The second element in each case + +is <datum>. This convention is supported so that arbitrary Scheme +programs may be represented as lists. + That is, according to Scheme's grammar, every +<expression> is also a <datum> (see section see section External representations). +Among other things, this permits the use of the read procedure to +parse Scheme programs. See section External representations. +

+ + +
(pair? obj)procedure
+ +

Pair? returns #t if obj is a pair, and otherwise +returns #f. +

+ +
 
(pair? '(a . b))                       ==>  #t
+(pair? '(a b c))                       ==>  #t
+(pair? '())                            ==>  #f
+(pair? '#(a b))                        ==>  #f
+
+ + + + + +
(cons obj1 obj2)procedure
+ +

Returns a newly allocated pair whose car is obj1 and whose cdr is +obj2. The pair is guaranteed to be different (in the sense of +eqv?) from every existing object. +

+ +
 
(cons 'a '())                          ==>  (a)
+(cons '(a) '(b c d))                   ==>  ((a) b c d)
+(cons "a" '(b c))                      ==>  ("a" b c)
+(cons 'a 3)                            ==>  (a . 3)
+(cons '(a b) 'c)                       ==>  ((a b) . c)
+
+ + + + + +
(car pair)procedure
+ + +

Returns the contents of the car field of pair. Note that it is an +error to take the car of the empty list. + +

+ +
 
(car '(a b c))                         ==>  a
+(car '((a) b c d))                     ==>  (a)
+(car '(1 . 2))                         ==>  1
+(car '())                              ==>  error
+
+ + + + + + +
(cdr pair)procedure
+ + +

Returns the contents of the cdr field of pair. +Note that it is an error to take the cdr of the empty list. +

+ +
 
(cdr '((a) b c d))                     ==>  (b c d)
+(cdr '(1 . 2))                         ==>  2
+(cdr '())                              ==>  error
+
+ + + + + + +
(set-car! pair obj)procedure
+ + +

Stores obj in the car field of pair. +The value returned by set-car! is unspecified. +

+ +
 
(define (f) (list 'not-a-constant-list))
+(define (g) '(constant-list))
+(set-car! (f) 3)                       ==>  unspecified
+(set-car! (g) 3)                       ==>  error
+
+ + + + + + +
(set-cdr! pair obj)procedure
+ + +

Stores obj in the cdr field of pair. +The value returned by set-cdr! is unspecified. +

+ + + + + + + +
(caar pair)library procedure
+
(cadr pair)library procedure
+
+
(cdddar pair)library procedure
+
(cddddr pair)library procedure
+ +

These procedures are compositions of car and cdr, where +for example caddr could be defined by +

+ +
 
(define caddr (lambda (x) (car (cdr (cdr x))))).
+
+ + +

Arbitrary compositions, up to four deep, are provided. There are +twenty-eight of these procedures in all. +

+ + + + +
(null? obj)library procedure
+ +

Returns #t if obj is the empty list, + +otherwise returns #f. +

+ + + + +
(list? obj)library procedure
+ +

Returns #t if obj is a list, otherwise returns #f. +By definition, all lists have finite length and are terminated by +the empty list. +

+ +
 
        (list? '(a b c))               ==>  #t
+        (list? '())                    ==>  #t
+        (list? '(a . b))               ==>  #f
+        (let ((x (list 'a)))
+          (set-cdr! x x)
+          (list? x))                   ==>  #f
+
+ + + + + +
(list obj)library procedure
+ +

Returns a newly allocated list of its arguments. +

+ +
 
(list 'a (+ 3 4) 'c)                   ==>  (a 7 c)
+(list)                                 ==>  ()
+
+ + + + + +
(length list)library procedure
+ + +

Returns the length of list. +

+ +
 
(length '(a b c))                      ==>  3
+(length '(a (b) (c d e)))              ==>  3
+(length '())                           ==>  0
+
+ + + + + +
(append list …)library procedure
+ + +

Returns a list consisting of the elements of the first list +followed by the elements of the other lists. +

+ +
 
(append '(x) '(y))                     ==>  (x y)
+(append '(a) '(b c d))                 ==>  (a b c d)
+(append '(a (b)) '((c)))               ==>  (a (b) (c))
+
+ + +

The resulting list is always newly allocated, except that it shares +structure with the last list argument. The last argument may +actually be any object; an improper list results if the last argument is not a +proper list. +

+ + +
 
(append '(a b) '(c . d))               ==>  (a b c . d)
+(append '() 'a)                        ==>  a
+
+ + + + + +
(reverse list)library procedure
+ + +

Returns a newly allocated list consisting of the elements of list +in reverse order. +

+ +
 
(reverse '(a b c))                     ==>  (c b a)
+(reverse '(a (b c) d (e (f))))  
+          ==>  ((e (f)) d (b c) a)
+
+ + + + + +
(list-tail list k)library procedure
+ +

Returns the sublist of list obtained by omitting the first k +elements. It is an error if list has fewer than k elements. +List-tail could be defined by +

+ +
 
(define list-tail
+  (lambda (x k)
+    (if (zero? k)
+        x
+        (list-tail (cdr x) (- k 1)))))
+
+ + + + + +
(list-ref list k)library procedure
+ +

Returns the kth element of list. (This is the same +as the car of (list-tail list k).) +It is an error if list has fewer than k elements. +

+ +
 
(list-ref '(a b c d) 2)                 ==>  c
+(list-ref '(a b c d)
+          (inexact->exact (round 1.8))) 
+          ==>  c
+
+ + + + + + + + + + +
(memq obj list)library procedure
+
(memv obj list)library procedure
+
(member obj list)library procedure
+ +

These procedures return the first sublist of list whose car is +obj, where the sublists of list are the non-empty lists +returned by (list-tail list k) for k less +than the length of list. If +obj does not occur in list, then #f (not the empty list) is +returned. Memq uses eq? to compare obj with the elements of +list, while memv uses eqv? and member uses equal?. +

+ +
 
(memq 'a '(a b c))                     ==>  (a b c)
+(memq 'b '(a b c))                     ==>  (b c)
+(memq 'a '(b c d))                     ==>  #f
+(memq (list 'a) '(b (a) c))            ==>  #f
+(member (list 'a)
+        '(b (a) c))                    ==>  ((a) c)
+(memq 101 '(100 101 102))              ==>  unspecified
+(memv 101 '(100 101 102))              ==>  (101 102)
+
+ + + + + + +
(assq obj alist)library procedure
+
(assv obj alist)library procedure
+
(assoc obj alist)library procedure
+ +

Alist (for “association list”) must be a list of +pairs. These procedures find the first pair in alist whose car field is obj, +and returns that pair. If no pair in alist has obj as its +car, then #f (not the empty list) is returned. Assq uses +eq? to compare obj with the car fields of the pairs in alist, +while assv uses eqv? and assoc uses equal?. +

+ +
 
(define e '((a 1) (b 2) (c 3)))
+(assq 'a e)                            ==>  (a 1)
+(assq 'b e)                            ==>  (b 2)
+(assq 'd e)                            ==>  #f
+(assq (list 'a) '(((a)) ((b)) ((c))))
+                                       ==>  #f
+(assoc (list 'a) '(((a)) ((b)) ((c))))   
+                                       ==>  ((a))
+(assq 5 '((2 3) (5 7) (11 13)))    
+                                       ==>  unspecified
+(assv 5 '((2 3) (5 7) (11 13)))    
+                                       ==>  (5 7)
+
+ + + + +

Rationale: +Although they are ordinarily used as predicates, +memq, memv, member, assq, assv, and assoc do not +have question marks in their names because they return useful values rather +than just #t or #f. +

+ + + + +
+ + + + + + + + + + + +
Back: 6.3.2 Pairs and listsForward: 6.3.4 Characters   FastBack: 6. Standard proceduresUp: 6.3 Other data typesFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.3.3 Symbols

+ + + +

Symbols are objects whose usefulness rests on the fact that two +symbols are identical (in the sense of eqv?) if and only if their +names are spelled the same way. This is exactly the property needed to +represent identifiers in programs, and so most + +implementations of Scheme use them internally for that purpose. Symbols +are useful for many other applications; for instance, they may be used +the way enumerated values are used in Pascal. +

+

The rules for writing a symbol are exactly the same as the rules for +writing an identifier; see sections Identifiers +and Lexical structure. +

+

It is guaranteed that any symbol that has been returned as part of +a literal expression, or read using the read procedure, and +subsequently written out using the write procedure, will read back +in as the identical symbol (in the sense of eqv?). The +string->symbol procedure, however, can create symbols for +which this write/read invariance may not hold because their names +contain special characters or letters in the non-standard case. +

+ +

Note: +Some implementations of Scheme have a feature known as “slashification” +in order to guarantee write/read invariance for all symbols, but +historically the most important use of this feature has been to +compensate for the lack of a string data type. +

+

Some implementations also have “uninterned symbols”, which +defeat write/read invariance even in implementations with slashification, +and also generate exceptions to the rule that two symbols are the same +if and only if their names are spelled the same. +

+ + + + +
(symbol? obj)procedure
+ +

Returns #t if obj is a symbol, otherwise returns #f. +

+ +
 
(symbol? 'foo)                         ==>  #t
+(symbol? (car '(a b)))                 ==>  #t
+(symbol? "bar")                        ==>  #f
+(symbol? 'nil)                         ==>  #t
+(symbol? '())                          ==>  #f
+(symbol? #f)                           ==>  #f
+
+ + + + + +
(symbol->string symbol)procedure
+ +

Returns the name of symbol as a string. If the symbol was part of +an object returned as the value of a literal expression +(section see section Literal expressions) or by a call to the read procedure, +and its name contains alphabetic characters, then the string returned +will contain characters in the implementation's preferred standard +case—some implementations will prefer upper case, others lower case. +If the symbol was returned by string->symbol, the case of +characters in the string returned will be the same as the case in the +string that was passed to string->symbol. It is an error +to apply mutation procedures like string-set! to strings returned + +by this procedure. +

+

The following examples assume that the implementation's standard case is +lower case: +

+ +
 
(symbol->string 'flying-fish)     
+                                       ==>  "flying-fish"
+(symbol->string 'Martin)               ==>  "martin"
+(symbol->string
+   (string->symbol "Malvina"))     
+                                       ==>  "Malvina"
+
+ + + + + +
(string->symbol string)procedure
+ +

Returns the symbol whose name is string. This procedure can +create symbols with names containing special characters or letters in +the non-standard case, but it is usually a bad idea to create such +symbols because in some implementations of Scheme they cannot be read as +themselves. See symbol->string. +

+

The following examples assume that the implementation's standard case is +lower case: +

+ +
 
(eq? 'mISSISSIppi 'mississippi)  
+          ==>  #t
+(string->symbol "mISSISSIppi")  
+          ==>
+  the symbol with name "mISSISSIppi"
+(eq? 'bitBlt (string->symbol "bitBlt"))     
+          ==>  #f
+(eq? 'JollyWog
+     (string->symbol
+       (symbol->string 'JollyWog)))  
+          ==>  #t
+(string=? "K. Harper, M.D."
+          (symbol->string
+            (string->symbol "K. Harper, M.D.")))  
+          ==>  #t
+
+ + + + + +
+ + + + + + + + + + + +
Back: 6.3.3 SymbolsForward: 6.3.5 Strings   FastBack: 6. Standard proceduresUp: 6.3 Other data typesFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.3.4 Characters

+ + + +

Characters are objects that represent printed characters such as +letters and digits. +Characters are written using the notation #\<character> +or #\<character name>. +For example: +

+ + +
+
#\a
+
+
+

; lower case letter +

#\A +

; upper case letter +

#\( +

; left parenthesis +

#\ +

; the space character +

#\space +

; the preferred way to write a space +

#\newline +

; the newline character +

+ + + + +

Case is significant in #\<character>, but not in +#\<character name>. +

+

If <character> in +#\<character> is alphabetic, then the character +following <character> must be a delimiter character such as a +space or parenthesis. This rule resolves the ambiguous case where, for +example, the sequence of characters “#\ space” +could be taken to be either a representation of the space character or a +representation of the character “#\ s” followed +by a representation of the symbol “pace.” +

+ +

Characters written in the #\ notation are self-evaluating. +That is, they do not have to be quoted in programs. +

+

Some of the procedures that operate on characters ignore the +difference between upper case and lower case. The procedures that +ignore case have “-ci” (for “case +insensitive”) embedded in their names. +

+ + +
(char? obj)procedure
+ +

Returns #t if obj is a character, otherwise returns #f. +

+ + + + +
(char=? char1 char2)procedure
+
(char<? char1 char2)procedure
+
(char>? char1 char2)procedure
+
(char<=? char1 char2)procedure
+
(char>=? char1 char2)procedure
+ + + +

These procedures impose a total ordering on the set of characters. It +is guaranteed that under this ordering: +

+ + +
    +
  • +The upper case characters are in order. For example, (char<? #\A #\B) returns #t. +
  • +The lower case characters are in order. For example, (char<? #\a #\b) returns #t. +
  • +The digits are in order. For example, (char<? #\0 #\9) returns #t. +
  • +Either all the digits precede all the upper case letters, or vice versa. +
  • +Either all the digits precede all the lower case letters, or vice versa. + +
+ + +

Some implementations may generalize these procedures to take more than +two arguments, as with the corresponding numerical predicates. +

+ + + + +
(char-ci=? char1 char2)library procedure
+
(char-ci<? char1 char2)library procedure
+
(char-ci>? char1 char2)library procedure
+
(char-ci<=? char1 char2)library procedure
+
(char-ci>=? char1 char2)library procedure
+ + +

These procedures are similar to char=? et cetera, but they treat +upper case and lower case letters as the same. For example, (char-ci=? #\A #\a) returns #t. Some +implementations may generalize these procedures to take more than two +arguments, as with the corresponding numerical predicates. +

+ + + + +
(char-alphabetic? char)library procedure
+
(char-numeric? char)library procedure
+
(char-whitespace? char)library procedure
+
(char-upper-case? letter)library procedure
+
(char-lower-case? letter)library procedure
+ +

These procedures return #t if their arguments are alphabetic, +numeric, whitespace, upper case, or lower case characters, respectively, +otherwise they return #f. The following remarks, which are specific to +the ASCII character set, are intended only as a guide: The alphabetic characters +are the 52 upper and lower case letters. The numeric characters are the +ten decimal digits. The whitespace characters are space, tab, line +feed, form feed, and carriage return. +

+ + + + + + +
(char->integer char)procedure
+
(integer->char n)procedure
+ +

Given a character, char->integer returns an exact integer +representation of the character. Given an exact integer that is the image of +a character under char->integer, integer->char +returns that character. These procedures implement order-preserving isomorphisms +between the set of characters under the char<=? ordering and some + +subset of the integers under the <= ordering. That is, if +

+ +
 
(char<=? a b) ⇒ #t  and  (<= x y) ⇒ #t
+
+ + + +

and x and y are in the domain of +integer->char, then +

+ +
 
(<= (char->integer a)
+    (char->integer b))                 ==>  #t
+
+(char<=? (integer->char x)
+         (integer->char y))            ==>  #t
+
+ + + + + + +
(char-upcase char)library procedure
+
(char-downcase char)library procedure
+ + +

These procedures return a character char2 such that (char-ci=? char char2). In addition, if char is +alphabetic, then the result of char-upcase is upper case and the +result of char-downcase is lower case. +

+ + + +
+ + + + + + + + + + + +
Back: 6.3.4 CharactersForward: 6.3.6 Vectors   FastBack: 6. Standard proceduresUp: 6.3 Other data typesFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.3.5 Strings

+ + + +

Strings are sequences of characters. +Strings are written as sequences of characters enclosed within doublequotes +("). A doublequote can be written inside a string only by escaping +it with a backslash (\), as in +

+ +
 
+"The word \"recursion\" has many meanings."
+
+ + +

A backslash can be written inside a string only by escaping it with another +backslash. Scheme does not specify the effect of a backslash within a +string that is not followed by a doublequote or backslash. +

+

A string constant may continue from one line to the next, but +the exact contents of such a string are unspecified. +

+

The length of a string is the number of characters that it +contains. This number is an exact, non-negative integer that is fixed when the +string is created. The valid indexes of a string are the + +exact non-negative integers less than the length of the string. The first +character of a string has index 0, the second has index 1, and so on. +

+

In phrases such as “the characters of string beginning with +index start and ending with index end,” it is understood +that the index start is inclusive and the index end is +exclusive. Thus if start and end are the same index, a null +substring is referred to, and if start is zero and end is +the length of string, then the entire string is referred to. +

+

Some of the procedures that operate on strings ignore the +difference between upper and lower case. The versions that ignore case +have “-ci” (for “case insensitive”) embedded in their +names. +

+ + +
(string? obj)procedure
+ +

Returns #t if obj is a string, otherwise returns #f. +

+ + + +
(make-string k)procedure
+
(make-string k char)procedure
+ +

Make-string returns a newly allocated string of +length k. If char is given, then all elements of the string +are initialized to char, otherwise the contents of the +string are unspecified. +

+ + + +
(string char …)library procedure
+ +

Returns a newly allocated string composed of the arguments. +

+ + + +
(string-length string)procedure
+ +

Returns the number of characters in the given string. +

+ + + +
(string-ref string k)procedure
+ +

k must be a valid index of string. +String-ref returns character k of string using zero-origin indexing. +

+ + + +
(string-set! string k char)procedure
+ + +

k must be a valid index of string +. +String-set! stores char in element k of string +and returns an unspecified value. +

+ +
 
(define (f) (make-string 3 #\*))
+(define (g) "***")
+(string-set! (f) 0 #\?)                ==>  unspecified
+(string-set! (g) 0 #\?)                ==>  error
+(string-set! (symbol->string 'immutable)
+             0
+             #\?)                      ==>  error
+
+ + + + + + +
(string=? string1 string2)library procedure
+
(string-ci=? string1 string2)library procedure
+ +

Returns #t if the two strings are the same length and contain the same +characters in the same positions, otherwise returns #f. +String-ci=? treats +upper and lower case letters as though they were the same character, but +string=? treats upper and lower case as distinct characters. +

+ + + + +
(string<? string1 string2)library procedure
+
(string>? string1 string2)library procedure
+
(string<=? string1 string2)library procedure
+
(string>=? string1 string2)library procedure
+
(string-ci<? string1 string2)library procedure
+
(string-ci>? string1 string2)library procedure
+
(string-ci<=? string1 string2)library procedure
+
(string-ci>=? string1 string2)library procedure
+ +

These procedures are the lexicographic extensions to strings of the +corresponding orderings on characters. For example, string<? is +the lexicographic ordering on strings induced by the ordering +char<? on characters. If two strings differ in length but +are the same up to the length of the shorter string, the shorter string +is considered to be lexicographically less than the longer string. +

+

Implementations may generalize these and the string=? and +string-ci=? procedures to take more than two arguments, as with +the corresponding numerical predicates. +

+ + + + +
(substring string start end)library procedure
+ +

String must be a string, and start and end +must be exact integers satisfying +

+ +

0 <= start <= end <= (string-length string). +

+

Substring returns a newly allocated string formed from the characters of +string beginning with index start (inclusive) and ending with index +end (exclusive). +

+ + + +
(string-append string)library procedure
+ +

Returns a newly allocated string whose characters form the concatenation of the +given strings. +

+ + + + +
(string->list string)library procedure
+
(list->string list)library procedure
+ +

String->list returns a newly allocated list of the +characters that make up the given string. List->string +returns a newly allocated string formed from the characters in the list +list, which must be a list of characters. String->list +and list->string are +inverses so far as equal? is concerned. +

+ + + + +
(string-copy string)library procedure
+ +

Returns a newly allocated copy of the given string. +

+ + + + +
(string-fill! string char)library procedure
+ +

Stores char in every element of the given string and returns an +unspecified value. +

+ + + +
+ + + + + + + + + + + +
Back: 6.3.5 StringsForward: 6.4 Control features   FastBack: 6. Standard proceduresUp: 6.3 Other data typesFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.3.6 Vectors

+ + + +

Vectors are heterogeneous structures whose elements are indexed +by integers. A vector typically occupies less space than a list +of the same length, and the average time required to access a randomly +chosen element is typically less for the vector than for the list. +

+

The length of a vector is the number of elements that it +contains. This number is a non-negative integer that is fixed when the +vector is created. The valid indexes of a + +vector are the exact non-negative integers less than the length of the +vector. The first element in a vector is indexed by zero, and the last +element is indexed by one less than the length of the vector. +

+

Vectors are written using the notation #(obj …). +For example, a vector of length 3 containing the number zero in element +0, the list (2 2 2 2) in element 1, and the string "Anna" in +element 2 can be written as following: +

+ +
 
+#(0 (2 2 2 2) "Anna")
+
+ + +

Note that this is the external representation of a vector, not an +expression evaluating to a vector. Like list constants, vector +constants must be quoted: +

+ +
 
+'#(0 (2 2 2 2) "Anna")  
+          ==>  #(0 (2 2 2 2) "Anna")
+
+
+ + + + + + +
(vector? obj)procedure
+ +

Returns #t if obj is a vector, otherwise returns #f. +

+ + + +
(make-vector k)procedure
+
(make-vector k fill)procedure
+ +

Returns a newly allocated vector of k elements. If a second +argument is given, then each element is initialized to fill. +Otherwise the initial contents of each element is unspecified. +

+ + + + +
(vector obj …)library procedure
+ +

Returns a newly allocated vector whose elements contain the given +arguments. Analogous to list. +

+ +
 
(vector 'a 'b 'c)                      ==>  #(a b c)
+
+ + + + + +
(vector-length vector)procedure
+ +

Returns the number of elements in vector as an exact integer. +

+ + + +
(vector-ref vector k)procedure
+ +

k must be a valid index of vector. +Vector-ref returns the contents of element k of +vector. +

+ +
 
(vector-ref '#(1 1 2 3 5 8 13 21)
+            5)  
+          ==>  8
+(vector-ref '#(1 1 2 3 5 8 13 21)
+            (let ((i (round (* 2 (acos -1)))))
+              (if (inexact? i)
+                  (inexact->exact i)
+                  i))) 
+          ==> 13
+
+ + + + + +
(vector-set! vector k obj)procedure
+ +

k must be a valid index of vector. +Vector-set! stores obj in element k of vector. +The value returned by vector-set! is unspecified. +

+ +
 
(let ((vec (vector 0 '(2 2 2 2) "Anna")))
+  (vector-set! vec 1 '("Sue" "Sue"))
+  vec)      
+          ==>  #(0 ("Sue" "Sue") "Anna")
+
+(vector-set! '#(0 1 2) 1 "doe")  
+          ==>  error  ; constant vector
+
+ + + + + +
(vector->list vector)library procedure
+
(list->vector list)library procedure
+ +

Vector->list returns a newly allocated list of the objects contained +in the elements of vector. List->vector returns a newly +created vector initialized to the elements of the list list. +

+ +
 
(vector->list '#(dah dah didah))  
+          ==>  (dah dah didah)
+(list->vector '(dididit dah))   
+          ==>  #(dididit dah)
+
+ + + + + +
(vector-fill! vector fill)library procedure
+ +

Stores fill in every element of vector. +The value returned by vector-fill! is unspecified. +

+ + + +
+ + + + + + + + + + + +
Back: 6.3.6 VectorsForward: 6.5 Eval   FastBack: 6. Standard proceduresUp: 6. Standard proceduresFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.4 Control features

+ + + + +

This chapter describes various primitive procedures which control the +flow of program execution in special ways. +The procedure? predicate is also described here. +

+ + + +
(procedure? obj)procedure
+ +

Returns #t if obj is a procedure, otherwise returns #f. +

+ +
 
(procedure? car)                       ==>  #t
+(procedure? 'car)                      ==>  #f
+(procedure? (lambda (x) (* x x)))   
+                                       ==>  #t
+(procedure? '(lambda (x) (* x x)))  
+                                       ==>  #f
+(call-with-current-continuation procedure?)
+                                       ==>  #t
+
+ + + + + + +
(apply proc arg1 … args)procedure
+ +

Proc must be a procedure and args must be a list. +Calls proc with the elements of the list +(append (list arg1 …) args) as the actual +arguments. +

+ +
 
(apply + (list 3 4))                   ==>  7
+
+(define compose
+  (lambda (f g)
+    (lambda args
+      (f (apply g args)))))
+
+((compose sqrt *) 12 75)               ==>  30
+
+ + + + + +
(map proc list1 list2 …)library procedure
+ +

The lists must be lists, and proc must be a +procedure taking as many arguments as there are lists +and returning a single value. If more +than one list is given, then they must all be the same length. +Map applies proc element-wise to the elements of the +lists and returns a list of the results, in order. +The dynamic order in which proc is applied to the elements of the +lists is unspecified. +

+ +
 
(map cadr '((a b) (d e) (g h)))   
+          ==>  (b e h)
+
+(map (lambda (n) (expt n n))
+     '(1 2 3 4 5))                
+          ==>  (1 4 27 256 3125)
+
+(map + '(1 2 3) '(4 5 6))              ==>  (5 7 9)
+
+(let ((count 0))
+  (map (lambda (ignored)
+         (set! count (+ count 1))
+         count)
+       '(a b)))                        ==>  (1 2) or (2 1)
+
+ + + + + + +
(for-each proc list1 list2 …)library procedure
+ +

The arguments to for-each are like the arguments to map, but +for-each calls proc for its side effects rather than for its +values. Unlike map, for-each is guaranteed to call proc on +the elements of the lists in order from the first element(s) to the +last, and the value returned by for-each is unspecified. +

+ +
 
(let ((v (make-vector 5)))
+  (for-each (lambda (i)
+              (vector-set! v i (* i i)))
+            '(0 1 2 3 4))
+  v)                                   ==>  #(0 1 4 9 16)
+
+ + + + + + +
(force promise)library procedure
+ +

Forces the value of promise (see delay, + +section see section Delayed evaluation). If no value has been computed for + +the promise, then a value is computed and returned. The value of the +promise is cached (or “memoized”) so that if it is forced a second +time, the previously computed value is returned. +

+ +
 
(force (delay (+ 1 2)))                ==>  3
+(let ((p (delay (+ 1 2))))
+  (list (force p) (force p)))  
+                                       ==>  (3 3)
+
+(define a-stream
+  (letrec ((next
+            (lambda (n)
+              (cons n (delay (next (+ n 1)))))))
+    (next 0)))
+(define head car)
+(define tail
+  (lambda (stream) (force (cdr stream))))
+
+(head (tail (tail a-stream)))  
+                                       ==>  2
+
+ + +

Force and delay are mainly intended for programs written in +functional style. The following examples should not be considered to +illustrate good programming style, but they illustrate the property that +only one value is computed for a promise, no matter how many times it is +forced. +

+ +
 
(define count 0)
+(define p
+  (delay (begin (set! count (+ count 1))
+                (if (> count x)
+                    count
+                    (force p)))))
+(define x 5)
+p                                      ==>  a promise
+(force p)                              ==>  6
+p                                      ==>  a promise, still
+(begin (set! x 10)
+       (force p))                      ==>  6
+
+ + +

Here is a possible implementation of delay and force. +Promises are implemented here as procedures of no arguments, +and force simply calls its argument: +

+ +
 
(define force
+  (lambda (object)
+    (object)))
+
+ + +

We define the expression +

+ +
 
(delay <expression>)
+
+ + +

to have the same meaning as the procedure call +

+ +
 
(make-promise (lambda () <expression>))
+
+ + +

as follows +

+ +
 
(define-syntax delay
+  (syntax-rules ()
+    ((delay expression)
+     (make-promise (lambda () expression))))),
+
+ + +

where make-promise is defined as follows: +

+ + +
 
(define make-promise
+  (lambda (proc)
+    (let ((result-ready? #f)
+          (result #f))
+      (lambda ()
+        (if result-ready?
+            result
+            (let ((x (proc)))
+              (if result-ready?
+                  result
+                  (begin (set! result-ready? #t)
+                         (set! result x)
+                         result))))))))
+
+ + + +

Rationale: +A promise may refer to its own value, as in the last example above. +Forcing such a promise may cause the promise to be forced a second time +before the value of the first force has been computed. +This complicates the definition of make-promise. +

+ + +

Various extensions to this semantics of delay and force +are supported in some implementations: +

+ + +
    +
  • +Calling force on an object that is not a promise may simply +return the object. + +
  • +It may be the case that there is no means by which a promise can be +operationally distinguished from its forced value. That is, expressions +like the following may evaluate to either #t or to #f, +depending on the implementation: + + +
     
    (eqv? (delay 1) 1)                ==>  unspecified
    +(pair? (delay (cons 1 2)))        ==>  unspecified
    +
    + + +
  • +Some implementations may implement “implicit forcing,” where +the value of a promise is forced by primitive procedures like cdr +and +: + + +
     
    (+ (delay (* 3 7)) 13)            ==>  34
    +
    + + +
+ + + + +
(call-with-current-continuation proc)procedure
+ +

Proc must be a procedure of one +argument. The procedure call-with-current-continuation packages +up the current continuation (see the rationale below) as an “escape +procedure” and passes it as an argument to + +proc. The escape procedure is a Scheme procedure that, if it is +later called, will abandon whatever continuation is in effect at that later +time and will instead use the continuation that was in effect +when the escape procedure was created. Calling the escape procedure +may cause the invocation of before and after thunks installed using +dynamic-wind. + +

+

The escape procedure accepts the same number of arguments as the continuation to +the original call to call-with-current-continuation. +Except for continuations created by the call-with-values +procedure, all continuations take exactly one value. The +effect of passing no value or more than one value to continuations +that were not created by call-with-values is unspecified. +

+

The escape procedure that is passed to proc has +unlimited extent just like any other procedure in Scheme. It may be stored +in variables or data structures and may be called as many times as desired. +

+

The following examples show only the most common ways in which +call-with-current-continuation is used. If all real uses were as +simple as these examples, there would be no need for a procedure with +the power of call-with-current-continuation. +

+ +
 
(call-with-current-continuation
+  (lambda (exit)
+    (for-each (lambda (x)
+                (if (negative? x)
+                    (exit x)))
+              '(54 0 37 -3 245 19))
+    #t))                               ==>  -3
+
+(define list-length
+  (lambda (obj)
+    (call-with-current-continuation
+      (lambda (return)
+        (letrec ((r
+                  (lambda (obj)
+                    (cond ((null? obj) 0)
+                          ((pair? obj)
+                           (+ (r (cdr obj)) 1))
+                          (else (return #f))))))
+          (r obj))))))
+
+(list-length '(1 2 3 4))               ==>  4
+
+(list-length '(a b . c))               ==>  #f
+
+ + + +

Rationale: +

+

A common use of call-with-current-continuation is for +structured, non-local exits from loops or procedure bodies, but in fact +call-with-current-continuation is extremely useful for implementing a +wide variety of advanced control structures. +

+

Whenever a Scheme expression is evaluated there is a +continuation wanting the result of the expression. The continuation + +represents an entire (default) future for the computation. If the expression is +evaluated at top level, for example, then the continuation might take the +result, print it on the screen, prompt for the next input, evaluate it, and +so on forever. Most of the time the continuation includes actions +specified by user code, as in a continuation that will take the result, +multiply it by the value stored in a local variable, add seven, and give +the answer to the top level continuation to be printed. Normally these +ubiquitous continuations are hidden behind the scenes and programmers do not +think much about them. On rare occasions, however, a programmer may +need to deal with continuations explicitly. +Call-with-current-continuation allows Scheme programmers to do +that by creating a procedure that acts just like the current +continuation. +

+

Most programming languages incorporate one or more special-purpose +escape constructs with names like exit, return, or +even goto. In 1965, however, Peter Landin [Landin65] +invented a general purpose escape operator called the J-operator. John +Reynolds [Reynolds72] described a simpler but equally powerful +construct in 1972. The catch special form described by Sussman +and Steele in the 1975 report on Scheme is exactly the same as +Reynolds's construct, though its name came from a less general construct +in MacLisp. Several Scheme implementors noticed that the full power of the +catch construct could be provided by a procedure instead of by a + +special syntactic construct, and the name +call-with-current-continuation was coined in 1982. This name is +descriptive, but opinions differ on the merits of such a long name, and +some people use the name call/cc instead. + +

+ + + + + +
(values obj …)procedure
+ +

Delivers all of its arguments to its continuation. +Except for continuations created by the call-with-values + +procedure, all continuations take exactly one value. +Values might be defined as follows: +

+
 
(define (values . things)
+  (call-with-current-continuation 
+    (lambda (cont) (apply cont things))))
+
+ + + + + +
(call-with-values producer consumer)procedure
+ +

Calls its producer argument with no values and +a continuation that, when passed some values, calls the +consumer procedure with those values as arguments. +The continuation for the call to consumer is the +continuation of the call to call-with-values. +

+ +
 
(call-with-values (lambda () (values 4 5))
+                  (lambda (a b) b))
+                                                   ==>  5
+
+(call-with-values * -)                             ==>  -1
+
+ + + + + +
(dynamic-wind before thunk after)procedure
+ +

Calls thunk without arguments, returning the result(s) of this call. +Before and after are called, also without arguments, as required +by the following rules (note that in the absence of calls to continuations +captured using call-with-current-continuation the three arguments are + +called once each, in order). Before is called whenever execution +enters the dynamic extent of the call to thunk and after is called +whenever it exits that dynamic extent. The dynamic extent of a procedure +call is the period between when the call is initiated and when it +returns. In Scheme, because of call-with-current-continuation, the +dynamic extent of a call may not be a single, connected time period. +It is defined as follows: +

+ +
    +
  • +The dynamic extent is entered when execution of the body of the +called procedure begins. + +
  • +The dynamic extent is also entered when execution is not within +the dynamic extent and a continuation is invoked that was captured +(using call-with-current-continuation) during the dynamic extent. + +
  • +It is exited when the called procedure returns. + +
  • +It is also exited when execution is within the dynamic extent and +a continuation is invoked that was captured while not within the +dynamic extent. + +
+ + +

If a second call to dynamic-wind occurs within the dynamic extent of the +call to thunk and then a continuation is invoked in such a way that the +afters from these two invocations of dynamic-wind are both to be +called, then the after associated with the second (inner) call to +dynamic-wind is called first. +

+

If a second call to dynamic-wind occurs within the dynamic extent of the +call to thunk and then a continuation is invoked in such a way that the +befores from these two invocations of dynamic-wind are both to be +called, then the before associated with the first (outer) call to +dynamic-wind is called first. +

+

If invoking a continuation requires calling the before from one call +to dynamic-wind and the after from another, then the after +is called first. +

+

The effect of using a captured continuation to enter or exit the dynamic +extent of a call to before or after is undefined. +

+ +
 
(let ((path '())
+      (c #f))
+  (let ((add (lambda (s)
+               (set! path (cons s path)))))
+    (dynamic-wind
+      (lambda () (add 'connect))
+      (lambda ()
+        (add (call-with-current-continuation
+               (lambda (c0)
+                 (set! c c0)
+                 'talk1))))
+      (lambda () (add 'disconnect)))
+    (if (< (length path) 4)
+        (c 'talk2)
+        (reverse path))))
+    
+          ==> (connect talk1 disconnect
+               connect talk2 disconnect)
+
+ + + +
+ + + + + + + + + + + +
Back: 6.4 Control featuresForward: 6.6 Input and output   FastBack: 6. Standard proceduresUp: 6. Standard proceduresFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.5 Eval

+ + + +
(eval expression environment-specifier)procedure
+ +

Evaluates expression in the specified environment and returns its value. +Expression must be a valid Scheme expression represented as data, +and environment-specifier must be a value returned by one of the +three procedures described below. +Implementations may extend eval to allow non-expression programs +(definitions) as the first argument and to allow other +values as environments, with the restriction that eval is not +allowed to create new bindings in the environments associated with +null-environment or scheme-report-environment. +

+ +
 
(eval '(* 7 3) (scheme-report-environment 5))
+                                                   ==>  21
+
+(let ((f (eval '(lambda (f x) (f x x))
+               (null-environment 5))))
+  (f + 10))
+                                                   ==>  20
+
+ + + + + +
(scheme-report-environment version)procedure
+
(null-environment version)procedure
+ +

Version must be the exact integer 5, +corresponding to this revision of the Scheme report (the +Revised^5 Report on Scheme). +Scheme-report-environment returns a specifier for an +environment that is empty except for all bindings defined in +this report that are either required or both optional and +supported by the implementation. Null-environment returns +a specifier for an environment that is empty except for the +(syntactic) bindings for all syntactic keywords defined in +this report that are either required or both optional and +supported by the implementation. +

+

Other values of version can be used to specify environments +matching past revisions of this report, but their support is not +required. An implementation will signal an error if version +is neither 5 nor another value supported by +the implementation. +

+

The effect of assigning (through the use of eval) a variable +bound in a scheme-report-environment +(for example car) is unspecified. Thus the environments specified +by scheme-report-environment may be immutable. +

+ + + +
(interaction-environment)optional procedure
+ +

This procedure returns a specifier for the environment that +contains implementation-defined bindings, typically a superset of +those listed in the report. The intent is that this procedure +will return the environment in which the implementation would evaluate +expressions dynamically typed by the user. +

+ + +
+ + + + + + + + + + + +
Back: 6.5 EvalForward: 6.6.1 Ports   FastBack: 6. Standard proceduresUp: 6. Standard proceduresFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.6 Input and output

+ + + + + + + + + +
+ + + + + + + + + + + +
Back: 6.6 Input and outputForward: 6.6.2 Input   FastBack: 6. Standard proceduresUp: 6.6 Input and outputFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.6.1 Ports

+ + + +

Ports represent input and output devices. To Scheme, an input port is a +Scheme object that can deliver characters upon command, while an output port +is a Scheme object that can accept characters. + +

+ + + +
(call-with-input-file string proc)library procedure
+
(call-with-output-file string proc)library procedure
+ +

String should be a string naming a file, and +proc should be a procedure that accepts one argument. +For call-with-input-file, +the file should already exist; for +call-with-output-file, +the effect is unspecified if the file +already exists. These procedures call proc with one argument: the +port obtained by opening the named file for input or output. If the +file cannot be opened, an error is signalled. If proc returns, +then the port is closed automatically and the value(s) yielded by the +proc is(are) returned. If proc does not return, then +the port will not be closed automatically unless it is possible to +prove that the port will never again be used for a read or write +operation. +

+ +

Rationale: +Because Scheme's escape procedures have unlimited extent, it is +possible to escape from the current continuation but later to escape back in. +If implementations were permitted to close the port on any escape from the +current continuation, then it would be impossible to write portable code using +both call-with-current-continuation and call-with-input-file or +call-with-output-file. +

+
+ + + + + +
(input-port? obj)procedure
+
(output-port? obj)procedure
+ +

Returns #t if obj is an input port or output port +respectively, otherwise returns #f. +

+ + + + + + +
(current-input-port)procedure
+
(current-output-port)procedure
+ +

Returns the current default input or output port. +

+ + + + +
(with-input-from-file string thunk)optional procedure
+
(with-output-to-file string thunk)optional procedure
+ +

String should be a string naming a file, and +proc should be a procedure of no arguments. +For with-input-from-file, +the file should already exist; for +with-output-to-file, +the effect is unspecified if the file +already exists. +The file is opened for input or output, an input or output port +connected to it is made the default value returned by +current-input-port or current-output-port +(and is used by (read), (write obj), and so forth), +and the +thunk is called with no arguments. When the thunk returns, +the port is closed and the previous default is restored. +With-input-from-file and with-output-to-file return(s) the +value(s) yielded by thunk. +If an escape procedure +is used to escape from the continuation of these procedures, their +behavior is implementation dependent. +

+ + + + + + + + + +
(open-input-file filename)procedure
+ +

Takes a string naming an existing file and returns an input port capable of +delivering characters from the file. If the file cannot be opened, an error is +signalled. +

+ + + + +
(open-output-file filename)procedure
+ +

Takes a string naming an output file to be created and returns an output +port capable of writing characters to a new file by that name. If the file +cannot be opened, an error is signalled. If a file with the given name +already exists, the effect is unspecified. +

+ + + + +
(close-input-port port)procedure
+
(close-output-port port)procedure
+ +

Closes the file associated with port, rendering the port +incapable of delivering or accepting characters. +

+

These routines have no effect if the file has already been closed. +The value returned is unspecified. +

+ + + + + + + +
+ + + + + + + + + + + +
Back: 6.6.1 PortsForward: 6.6.3 Output   FastBack: 6. Standard proceduresUp: 6.6 Input and outputFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.6.2 Input

+ + + + +

+
+
+
+
+
+

+ + +
(read)library procedure
+
(read port)library procedure
+ +

Read converts external representations of Scheme objects into the +objects themselves. That is, it is a parser for the nonterminal +<datum> (see sections see section External representations and +see section Pairs and lists). Read returns the next +object parsable from the given input port, updating port to point to +the first character past the end of the external representation of the object. +

+

If an end of file is encountered in the input before any +characters are found that can begin an object, then an end of file +object is returned. + The port remains open, and further attempts +to read will also return an end of file object. If an end of file is +encountered after the beginning of an object's external representation, +but the external representation is incomplete and therefore not parsable, +an error is signalled. +

+

The port argument may be omitted, in which case it defaults to the +value returned by current-input-port. It is an error to read from +a closed port. +

+ + +
(read-char)procedure
+
(read-char port)procedure
+ +

Returns the next character available from the input port, updating +the port to point to the following character. If no more characters +are available, an end of file object is returned. Port may be +omitted, in which case it defaults to the value returned by current-input-port. +

+ + + + +
(peek-char)procedure
+
(peek-char port)procedure
+ +

Returns the next character available from the input port, +without updating +the port to point to the following character. If no more characters +are available, an end of file object is returned. Port may be +omitted, in which case it defaults to the value returned by current-input-port. +

+ +

Note: +The value returned by a call to peek-char is the same as the +value that would have been returned by a call to read-char with the +same port. The only difference is that the very next call to +read-char or peek-char on that port will return the +value returned by the preceding call to peek-char. In particular, a call +to peek-char on an interactive port will hang waiting for input +whenever a call to read-char would have hung. +

+ + + + + + +
(eof-object? obj)procedure
+ +

Returns #t if obj is an end of file object, otherwise returns +#f. The precise set of end of file objects will vary among +implementations, but in any case no end of file object will ever be an object +that can be read in using read. +

+ + + + +
(char-ready?)procedure
+
(char-ready? port)procedure
+ +

Returns #t if a character is ready on the input port and +returns #f otherwise. If char-ready returns #t then +the next read-char operation on the given port is guaranteed +not to hang. If the port is at end of file then char-ready? +returns #t. Port may be omitted, in which case it defaults to +the value returned by current-input-port. +

+ +

Rationale: +Char-ready? exists to make it possible for a program to +accept characters from interactive ports without getting stuck waiting for +input. Any input editors associated with such ports must ensure that +characters whose existence has been asserted by char-ready? cannot +be rubbed out. If char-ready? were to return #f at end of +file, a port at end of file would be indistinguishable from an interactive +port that has no ready characters. +

+ + + + +
+ + + + + + + + + + + +
Back: 6.6.2 InputForward: 6.6.4 System interface   FastBack: 6. Standard proceduresUp: 6.6 Input and outputFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.6.3 Output

+ + + + +

+
+
+
+
+
+

+ +
(write obj)library procedure
+
(write obj port)library procedure
+ +

Writes a written representation of obj to the given port. Strings +that appear in the written representation are enclosed in doublequotes, and +within those strings backslash and doublequote characters are +escaped by backslashes. +Character objects are written using the #\ notation. +Write returns an unspecified value. The +port argument may be omitted, in which case it defaults to the value +returned by current-output-port. +

+ + + + +
(display obj)library procedure
+
(display obj port)library procedure
+ +

Writes a representation of obj to the given port. Strings +that appear in the written representation are not enclosed in +doublequotes, and no characters are escaped within those strings. Character +objects appear in the representation as if written by write-char +instead of by write. Display returns an unspecified value. +The port argument may be omitted, in which case it defaults to the +value returned by current-output-port. +

+ +

Rationale: +Write is intended +for producing machine-readable output and display is for producing +human-readable output. Implementations that allow “slashification” +within symbols will probably want write but not display to +slashify funny characters in symbols. +

+ + + + + +
(newline)library procedure
+
(newline port)library procedure
+ +

Writes an end of line to port. Exactly how this is done differs +from one operating system to another. Returns an unspecified value. +The port argument may be omitted, in which case it defaults to the +value returned by current-output-port. +

+ + + + +
(write-char char)procedure
+
(write-char char port)procedure
+ +

Writes the character char (not an external representation of the +character) to the given port and returns an unspecified value. The +port argument may be omitted, in which case it defaults to the value +returned by current-output-port. +

+ + + +
+ + + + + + + + + + + +
Back: 6.6.3 OutputForward: 7. Formal syntax and semantics   FastBack: 6. Standard proceduresUp: 6.6 Input and outputFastForward: 7. Formal syntax and semanticsTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

6.6.4 System interface

+ + +

Questions of system interface generally fall outside of the domain of this +report. However, the following operations are important enough to +deserve description here. +

+ + +
(load filename)optional procedure
+ + + +

Filename should be a string naming an existing file +containing Scheme source code. The load procedure reads +expressions and definitions from the file and evaluates them +sequentially. It is unspecified whether the results of the expressions +are printed. The load procedure does not affect the values +returned by current-input-port and current-output-port. +Load returns an unspecified value. +

+ +

Rationale: +For portability, load must operate on source files. +Its operation on other kinds of files necessarily varies among +implementations. +

+ + + + + +
(transcript-on filename)optional procedure
+
(transcript-off)optional procedure
+ +

Filename must be a string naming an output file to be +created. The effect of transcript-on is to open the named file +for output, and to cause a transcript of subsequent interaction between +the user and the Scheme system to be written to the file. The +transcript is ended by a call to transcript-off, which closes the +transcript file. Only one transcript may be in progress at any time, +though some implementations may relax this restriction. The values +returned by these procedures are unspecified. +

+ + + + +
+ + + + + + + + + + + +
Back: 6.6.4 System interfaceForward: 7.1 Formal syntax   FastBack: 6. Standard proceduresUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7. Formal syntax and semantics

+ + + + + + + + + +

This chapter provides formal descriptions of what has already been +described informally in previous chapters of this report. +

+ + + +
+ + + + + + + + + + + +
Back: 7. Formal syntax and semanticsForward: 7.1.1 Lexical structure   FastBack: 7. Formal syntax and semanticsUp: 7. Formal syntax and semanticsFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.1 Formal syntax

+ + + + + + + + + + + + +

This section provides a formal syntax for Scheme written in an extended +BNF. +

+

All spaces in the grammar are for legibility. Case is insignificant; +for example, #x1A and #X1a are equivalent. <empty> +stands for the empty string. +

+

The following extensions to BNF are used to make the description more +concise: <thing>* means zero or more occurrences of +<thing>; and <thing>+ means at least one +<thing>. +

+ +
+ + + + + + + + + + + +
Back: 7.1 Formal syntaxForward: 7.1.2 External representations   FastBack: 7. Formal syntax and semanticsUp: 7.1 Formal syntaxFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.1.1 Lexical structure

+ + +

This section describes how individual tokens (identifiers, + +numbers, etc.) are formed from sequences of characters. The following +sections describe how expressions and programs are formed from sequences +of tokens. +

+

<Intertoken space> may occur on either side of any token, but not +within a token. +

+

Tokens which require implicit termination (identifiers, numbers, +characters, and dot) may be terminated by any <delimiter>, but not +necessarily by anything else. +

+

The following five characters are reserved for future extensions to the +language: [ ] { } | +

+ +
 
<token> –> <identifier> | <boolean> | <number>
+     | <character> | <string>
+     | ( | ) | #( | ' |  | , | ,@ | .
+<delimiter> –> <whitespace> | ( | ) | " | ;
+<whitespace> –> <space or newline>
+<comment> –> ;  <all subsequent characters up to a
+                 line break>
+<atmosphere> –> <whitespace> | <comment>
+<intertoken space> –> <atmosphere>*
+
+ + + + + + + + + +
 
<identifier> –> <initial> <subsequent>*
+     | <peculiar identifier>
+<initial> –> <letter> | <special initial>
+<letter> –> a | b | c | ... | z
+
+<special initial> –> ! | $ | % | & | * | / | : | < | =
+     | > | ? | ^ | _ | ~
+<subsequent> –> <initial> | <digit>
+     | <special subsequent>
+<digit> –> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
+<special subsequent> –> + | - | . | @
+<peculiar identifier> –> + | - | ...
+<syntactic keyword> –> <expression keyword>
+     | else | => | define 
+     | unquote | unquote-splicing
+<expression keyword> –> quote | lambda | if
+     | set! | begin | cond | and | or | case
+     | let | let* | letrec | do | delay
+     | quasiquote
+
+<variable> ⇒ <any <identifier> that isn't
+                also a <syntactic keyword>>
+
+<boolean> –> #t | #f
+<character> –> #\ <any character>
+     | #\ <character name>
+<character name> –> space | newline
+
+<string> –> " <string element>* "
+<string element> –> <any character other than " or \>
+     | \" | \\
+
+ + + + + + + +
 
<number> –> <num 2>| <num 8>
+     | <num 10>| <num 16>
+
+ + + +

The following rules for <num R>, <complex R>, <real +R>, <ureal R>, <uinteger R>, and <prefix R> +should be replicated for R = 2, 8, 10, +and 16. There are no rules for <decimal 2>, <decimal +8>, and <decimal 16>, which means that numbers containing +decimal points or exponents must be in decimal radix. +

+ + +
 
<num R> –> <prefix R> <complex R>
+<complex R> –> <real R> | <real R> @ <real R>
+    | <real R> + <ureal R> i | <real R> - <ureal R> i
+    | <real R> + i | <real R> - i
+    | + <ureal R> i | - <ureal R> i | + i | - i
+<real R> –> <sign> <ureal R>
+<ureal R> –> <uinteger R>
+    | <uinteger R> / <uinteger R>
+    | <decimal R>
+<decimal 10> –> <uinteger 10> <suffix>
+    | . <digit 10>+ #* <suffix>
+    | <digit 10>+ . <digit 10>* #* <suffix>
+    | <digit 10>+ #+ . #* <suffix>
+<uinteger R> –> <digit R>+ #*
+<prefix R> –> <radix R> <exactness>
+    | <exactness> <radix R>
+
+ + + + +
 
<suffix> –> <empty> 
+    | <exponent marker> <sign> <digit 10>+
+<exponent marker> –> e | s | f | d | l
+<sign> –> <empty>  | + |  -
+<exactness> –> <empty> | #i | #e
+<radix 2> –> #b
+<radix 8> –> #o
+<radix 10> –> <empty> | #d
+<radix 16> –> #x
+<digit 2> –> 0 | 1
+<digit 8> –> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
+<digit 10> –> <digit>
+<digit 16> –> <digit 10> | a | b | c | d | e | f
+
+ + + + + + +
+ + + + + + + + + + + +
Back: 7.1.1 Lexical structureForward: 7.1.3 Expressions   FastBack: 7. Formal syntax and semanticsUp: 7.1 Formal syntaxFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.1.2 External representations

+ + + +

<Datum> is what the read procedure (section see section Input) + +successfully parses. Note that any string that parses as an +<expression> will also parse as a <datum>. +

+ +
 
<datum> –> <simple datum> | <compound datum>
+<simple datum> –> <boolean> | <number>
+     | <character> | <string> |  <symbol>
+<symbol> –> <identifier>
+<compound datum> –> <list> | <vector>
+<list> –> (<datum>*) | (<datum>+ . <datum>)
+       | <abbreviation>
+<abbreviation> –> <abbrev prefix> <datum>
+<abbrev prefix> –> ' | ‘ | , | ,@
+<vector> –> #(<datum>*)
+
+ + + + +
+ + + + + + + + + + + +
Back: 7.1.2 External representationsForward: 7.1.4 Quasiquotations   FastBack: 7. Formal syntax and semanticsUp: 7.1 Formal syntaxFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.1.3 Expressions

+ + + +
 
<expression> –> <variable>
+     | <literal>
+     | <procedure call>
+     | <lambda expression>
+     | <conditional>
+     | <assignment>
+     | <derived expression>
+     | <macro use>
+     | <macro block>
+
+<literal> –> <quotation> | <self-evaluating>
+<self-evaluating> –> <boolean> | <number>
+     | <character> | <string>
+<quotation> –> '<datum> | (quote <datum>)
+<procedure call> –> (<operator> <operand>*)
+<operator> –> <expression>
+<operand> –> <expression>
+
+<lambda expression> –> (lambda <formals> <body>)
+<formals> –> (<variable>*) | <variable>
+     | (<variable>+ . <variable>)
+<body> –> <definition>* <sequence>
+<sequence> –> <command>* <expression>
+<command> –> <expression>
+
+<conditional> –> (if <test> <consequent> <alternate>)
+<test> –> <expression>
+<consequent> –> <expression>
+<alternate> –> <expression> | <empty>
+
+<assignment> –> (set! <variable> <expression>)
+
+<derived expression> –>
+       (cond <cond clause>+)
+     | (cond <cond clause>* (else <sequence>))
+     | (case <expression>
+         <case clause>+)
+     | (case <expression>
+         <case clause>*
+         (else <sequence>))
+     | (and <test>*)
+     | (or <test>*)
+     | (let (<binding spec>*) <body>)
+     | (let <variable> (<binding spec>*) <body>)
+     | (let* (<binding spec>*) <body>)
+     | (letrec (<binding spec>*) <body>)
+     | (begin <sequence>)
+     | (do (<iteration spec>*)
+           (<test> <do result>)
+         <command>*)
+     | (delay <expression>)
+     | <quasiquotation>
+
+<cond clause> –> (<test> <sequence>)
+      | (<test>)
+      | (<test> => <recipient>)
+<recipient> –> <expression>
+<case clause> –> ((<datum>*) <sequence>)
+<binding spec> –> (<variable> <expression>)
+<iteration spec> –> (<variable> <init> <step>)
+    | (<variable> <init>)
+<init> –> <expression>
+<step> –> <expression>
+<do result> –> <sequence> | <empty>
+
+<macro use> –> (<keyword> <datum>*)
+<keyword> –> <identifier>
+
+<macro block> –>
+     (let-syntax (<syntax spec>*) <body>)
+     | (letrec-syntax (<syntax spec>*) <body>)
+<syntax spec> –> (<keyword> <transformer spec>)
+
+ + + +
+ + + + + + + + + + + +
Back: 7.1.3 ExpressionsForward: 7.1.5 Transformers   FastBack: 7. Formal syntax and semanticsUp: 7.1 Formal syntaxFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.1.4 Quasiquotations

+ + +

The following grammar for quasiquote expressions is not context-free. +It is presented as a recipe for generating an infinite number of +production rules. Imagine a copy of the following rules for D = 1, 2,3, …. D keeps track of the nesting depth. +

+ +
 
<quasiquotation> –> <quasiquotation 1>
+<qq template 0> –> <expression>
+<quasiquotation D> –> ‘<qq template D>
+       | (quasiquote <qq template D>)
+<qq template D> –> <simple datum>
+       | <list qq template D>
+       | <vector qq template D>
+       | <unquotation D>
+<list qq template D> –> (<qq template or splice D>*)
+       | (<qq template or splice D>+ . <qq template D>)
+       | '<qq template D>
+       | <quasiquotation D+1>
+<vector qq template D> –> #(<qq template or splice D>*)
+<unquotation D> –> ,<qq template D-1>
+       | (unquote <qq template D-1>)
+<qq template or splice D> –> <qq template D>
+       | <splicing unquotation D>
+<splicing unquotation D> –> ,@<qq template D-1>
+       | (unquote-splicing <qq template D-1>)
+
+ + + +

In <quasiquotation>s, a <list qq template D> can sometimes +be confused with either an <unquotation D> or a <splicing +unquotation D>. The interpretation as an +<unquotation> or <splicing +unquotation D> takes precedence. +

+
+ + + + + + + + + + + +
Back: 7.1.4 QuasiquotationsForward: 7.1.6 Programs and definitions   FastBack: 7. Formal syntax and semanticsUp: 7.1 Formal syntaxFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.1.5 Transformers

+ + + +
 
<transformer spec> –>
+    (syntax-rules (<identifier>*) <syntax rule>*)
+<syntax rule> –> (<pattern> <template>)
+<pattern> –> <pattern identifier>
+     | (<pattern>*)
+     | (<pattern>+ . <pattern>)
+     | (<pattern>* <pattern> <ellipsis>)
+     | #(<pattern>*)
+     | #(<pattern>* <pattern> <ellipsis>)
+     | <pattern datum>
+<pattern datum> –> <string>
+     | <character>
+     | <boolean>
+     | <number>
+<template> –> <pattern identifier>
+     | (<template element>*)
+     | (<template element>+ . <template>)
+     | #(<template element>*)
+     | <template datum>
+<template element> –> <template>
+     | <template> <ellipsis>
+<template datum> –> <pattern datum>
+<pattern identifier> –> <any identifier except ...>
+<ellipsis> –> <the identifier ...>
+
+ + + +
+ + + + + + + + + + + +
Back: 7.1.5 TransformersForward: 7.2 Formal semantics   FastBack: 7. Formal syntax and semanticsUp: 7.1 Formal syntaxFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.1.6 Programs and definitions

+ + + +
 
<program> –> <command or definition>*
+<command or definition> –> <command>
+    | <definition>
+    | <syntax definition>
+    | (begin <command or definition>+)
+<definition> –> (define <variable> <expression>)
+      | (define (<variable> <def formals>) <body>)
+      | (begin <definition>*)
+<def formals> –> <variable>*
+      | <variable>* . <variable>
+<syntax definition> –>
+     (define-syntax <keyword> <transformer spec>)
+
+ + + +
+ + + + + + + + + + + +
Back: 7.1.6 Programs and definitionsForward: 7.3 Derived expression types   FastBack: 7. Formal syntax and semanticsUp: 7. Formal syntax and semanticsFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.2 Formal semantics

+ + +

This section provides a formal denotational semantics for the primitive +expressions of Scheme and selected built-in procedures. The concepts +and notation used here are described in [STOY77]. +

+

Note: The formal semantics section was written in LaTeX which +is incompatible with TeXinfo. See the Formal semantics section of +the original document from which this was derived. +

+ + +
+ + + + + + + + + + + +
Back: 7.2 Formal semanticsForward: Notes   FastBack: 7. Formal syntax and semanticsUp: 7. Formal syntax and semanticsFastForward: NotesTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

7.3 Derived expression types

+ + + +

This section gives macro definitions for the derived expression types in +terms of the primitive expression types (literal, variable, call, lambda, +if, set!). See section Control features for a possible +definition of delay. +

+ +
 
+(define-syntax cond
+  (syntax-rules (else =>)
+    ((cond (else result1 result2 ...))
+     (begin result1 result2 ...))
+    ((cond (test => result))
+     (let ((temp test))
+       (if temp (result temp))))
+    ((cond (test => result) clause1 clause2 ...)
+     (let ((temp test))
+       (if temp
+           (result temp)
+           (cond clause1 clause2 ...))))
+    ((cond (test)) test)
+    ((cond (test) clause1 clause2 ...)
+     (let ((temp test))
+       (if temp
+           temp
+           (cond clause1 clause2 ...))))
+    ((cond (test result1 result2 ...))
+     (if test (begin result1 result2 ...)))
+    ((cond (test result1 result2 ...)
+           clause1 clause2 ...)
+     (if test
+         (begin result1 result2 ...)
+         (cond clause1 clause2 ...)))))
+
+ + + +
 
+(define-syntax case
+  (syntax-rules (else)
+    ((case (key ...)
+       clauses ...)
+     (let ((atom-key (key ...)))
+       (case atom-key clauses ...)))
+    ((case key
+       (else result1 result2 ...))
+     (begin result1 result2 ...))
+    ((case key
+       ((atoms ...) result1 result2 ...))
+     (if (memv key '(atoms ...))
+         (begin result1 result2 ...)))
+    ((case key
+       ((atoms ...) result1 result2 ...)
+       clause clauses ...)
+     (if (memv key '(atoms ...))
+         (begin result1 result2 ...)
+         (case key clause clauses ...)))))
+
+ + + +
 
+(define-syntax and
+  (syntax-rules ()
+    ((and) #t)
+    ((and test) test)
+    ((and test1 test2 ...)
+     (if test1 (and test2 ...) #f))))
+
+ + + +
 
+(define-syntax or
+  (syntax-rules ()
+    ((or) #f)
+    ((or test) test)
+    ((or test1 test2 ...)
+     (let ((x test1))
+       (if x x (or test2 ...))))))
+
+ + + +
 
+(define-syntax let
+  (syntax-rules ()
+    ((let ((name val) ...) body1 body2 ...)
+     ((lambda (name ...) body1 body2 ...)
+      val ...))
+    ((let tag ((name val) ...) body1 body2 ...)
+     ((letrec ((tag (lambda (name ...)
+                      body1 body2 ...)))
+        tag)
+      val ...))))
+
+ + + +
 
+(define-syntax let*
+  (syntax-rules ()
+    ((let* () body1 body2 ...)
+     (let () body1 body2 ...))
+    ((let* ((name1 val1) (name2 val2) ...)
+       body1 body2 ...)
+     (let ((name1 val1))
+       (let* ((name2 val2) ...)
+         body1 body2 ...)))))
+
+ + +

The following letrec macro uses the symbol <undefined> +in place of an expression which returns something that when stored in +a location makes it an error to try to obtain the value stored in the +location (no such expression is defined in Scheme). +A trick is used to generate the temporary names needed to avoid +specifying the order in which the values are evaluated. +This could also be accomplished by using an auxiliary macro. +

+ +
 
+(define-syntax letrec
+  (syntax-rules ()
+    ((letrec ((var1 init1) ...) body ...)
+     (letrec "generate temp names"
+       (var1 ...)
+       ()
+       ((var1 init1) ...)
+       body ...))
+    ((letrec "generate temp names"
+       ()
+       (temp1 ...)
+       ((var1 init1) ...)
+       body ...)
+     (let ((var1 <undefined>) ...)
+       (let ((temp1 init1) ...)
+         (set! var1 temp1)
+         ...
+         body ...)))
+    ((letrec "generate temp names"
+       (x y ...)
+       (temp ...)
+       ((var1 init1) ...)
+       body ...)
+     (letrec "generate temp names"
+       (y ...)
+       (newtemp temp ...)
+       ((var1 init1) ...)
+       body ...))))
+
+ + + +
 
+(define-syntax begin
+  (syntax-rules ()
+    ((begin exp ...)
+     ((lambda () exp ...)))))
+
+ + +

The following alternative expansion for begin does not make use of +the ability to write more than one expression in the body of a lambda +expression. In any case, note that these rules apply only if the body +of the begin contains no definitions. +

+ +
 
+(define-syntax begin
+  (syntax-rules ()
+    ((begin exp)
+     exp)
+    ((begin exp1 exp2 ...)
+     (let ((x exp1))
+       (begin exp2 ...)))))
+
+ + +

The following definition +of do uses a trick to expand the variable clauses. +As with letrec above, an auxiliary macro would also work. +The expression (if #f #f) is used to obtain an unspecific +value. +

+ +
 
+(define-syntax do
+  (syntax-rules ()
+    ((do ((var init step ...) ...)
+         (test expr ...)
+         command ...)
+     (letrec
+       ((loop
+         (lambda (var ...)
+           (if test
+               (begin
+                 (if #f #f)
+                 expr ...)
+               (begin
+                 command
+                 ...
+                 (loop (do "step" var step ...)
+                       ...))))))
+       (loop init ...)))
+    ((do "step" x)
+     x)
+    ((do "step" x y)
+     y)))
+
+ + + + + +
+ + + + + + + + + + + +
Back: 7.3 Derived expression typesForward: Language changes   FastBack: 7. Formal syntax and semanticsUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: Additional materialTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Notes

+ + + + + + + + + +
+ + + + + + + + + + + +
Back: NotesForward: Additional material   FastBack: NotesUp: NotesFastForward: Additional materialTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Language changes

+ + + +

This section enumerates the changes that have been made to Scheme since +the “Revised^4 report” [R4RS] was published. +

+ + +
    +
  • +The report is now a superset of the IEEE standard for Scheme +[IEEEScheme]: implementations that conform to the report will +also conform to the standard. This required the following changes: + + +
      +
    • +The empty list is now required to count as true. + +
    • +The classification of features as essential or inessential has been +removed. There are now three classes of built-in procedures: primitive, +library, and optional. The optional procedures are load, +with-input-from-file, with-output-to-file, +transcript-on, transcript-off, and +interaction-environment, +and - and / with more than two arguments. +None of these are in the IEEE standard. + +
    • +Programs are allowed to redefine built-in procedures. Doing so +will not change the behavior of other built-in procedures. + +
    + + +
  • +Port has been added to the list of disjoint types. + +
  • +The macro appendix has been removed. High-level macros are now part +of the main body of the report. The rewrite rules for derived expressions +have been replaced with macro definitions. There are no reserved identifiers. + +
  • +Syntax-rules now allows vector patterns. + +
  • +Multiple-value returns, eval, and dynamic-wind have +been added. + +
  • +The calls that are required to be implemented in a properly tail-recursive +fashion are defined explicitly. + +
  • +‘@' can be used within identifiers. ‘|' is reserved +for possible future extensions. + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: Language changesForward: Example   FastBack: NotesUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: ExampleTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Additional material

+ + +

The Internet Scheme Repository at +

+ +

http://www.cs.indiana.edu/scheme-repository/ +

+ +

contains an extensive Scheme bibliography, as well as papers, +programs, implementations, and other material related to Scheme. +

+ + + +
+ + + + + + + + + + + +
Back: Additional materialForward: Bibliography   FastBack: Additional materialUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: BibliographyTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Example

+ + + +

Integrate-system integrates the system +

+ +

y_k^^ = f_k(y_1, y_2, … y_n), k = 1, … n +

+

of differential equations with the method of Runge-Kutta. +

+

The parameter system-derivative is a function that takes a system +state (a vector of values for the state variables y_1, … y_n) +and produces a system derivative (the values y_1^^, …y_n^^). The parameter initial-state provides an initial +system state, and h is an initial guess for the length of the +integration step. +

+

The value returned by integrate-system is an infinite stream of +system states. +

+ +
 
+(define integrate-system
+  (lambda (system-derivative initial-state h)
+    (let ((next (runge-kutta-4 system-derivative h)))
+      (letrec ((states
+                (cons initial-state
+                      (delay (map-streams next
+                                          states)))))
+        states))))
+
+ + +

Runge-Kutta-4 takes a function, f, that produces a +system derivative from a system state. Runge-Kutta-4 +produces a function that takes a system state and +produces a new system state. +

+ +
 
+(define runge-kutta-4
+  (lambda (f h)
+    (let ((*h (scale-vector h))
+          (*2 (scale-vector 2))
+          (*1/2 (scale-vector (/ 1 2)))
+          (*1/6 (scale-vector (/ 1 6))))
+      (lambda (y)
+        ;; y is a system state
+        (let* ((k0 (*h (f y)))
+               (k1 (*h (f (add-vectors y (*1/2 k0)))))
+               (k2 (*h (f (add-vectors y (*1/2 k1)))))
+               (k3 (*h (f (add-vectors y k2)))))
+          (add-vectors y
+            (*1/6 (add-vectors k0
+                               (*2 k1)
+                               (*2 k2)
+                               k3))))))))
+
+(define elementwise
+  (lambda (f)
+    (lambda vectors
+      (generate-vector
+        (vector-length (car vectors))
+        (lambda (i)
+          (apply f
+                 (map (lambda (v) (vector-ref  v i))
+                      vectors)))))))
+
+(define generate-vector
+  (lambda (size proc)
+    (let ((ans (make-vector size)))
+      (letrec ((loop
+                (lambda (i)
+                  (cond ((= i size) ans)
+                        (else
+                         (vector-set! ans i (proc i))
+                         (loop (+ i 1)))))))
+        (loop 0)))))
+
+(define add-vectors (elementwise +))
+
+(define scale-vector
+  (lambda (s)
+    (elementwise (lambda (x) (* x s)))))
+
+ + +

Map-streams is analogous to map: it applies its first +argument (a procedure) to all the elements of its second argument (a +stream). +

+ +
 
+(define map-streams
+  (lambda (f s)
+    (cons (f (head s))
+          (delay (map-streams f (tail s))))))
+
+ + +

Infinite streams are implemented as pairs whose car holds the first +element of the stream and whose cdr holds a promise to deliver the rest +of the stream. +

+ +
 
+(define head car)
+(define tail
+  (lambda (stream) (force (cdr stream))))
+
+ + +
+
+
+
+
+
+

The following illustrates the use of integrate-system in +integrating the system +

+ +

C dv_C / dt = -i_L - v_C / R +

+ + +

L di_L / dt = v_C +

+

which models a damped oscillator. +

+ +
 
+(define damped-oscillator
+  (lambda (R L C)
+    (lambda (state)
+      (let ((Vc (vector-ref state 0))
+            (Il (vector-ref state 1)))
+        (vector (- 0 (+ (/ Vc (* R C)) (/ Il C)))
+                (/ Vc L))))))
+
+(define the-states
+  (integrate-system
+     (damped-oscillator 10000 1000 .001)
+     '#(1 0)
+     .01))
+
+ + + + + + + + + + + + + +
+ + + + + + + + + + + +
Back: ExampleForward: Alphabetic index of definitions of concepts, keywords, and procedures   FastBack: ExampleUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: Alphabetic index of definitions of concepts, keywords, and proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Bibliography

+ + +
    +
  • [SICP] + +Harold Abelson and Gerald Jay Sussman with Julie Sussman. +Structure and Interpretation of Computer Programs, second edition. +MIT Press, Cambridge, 1996. + +
  • [Bawden88] +Alan Bawden and Jonathan Rees. + +Syntactic closures. +In Proceedings of the 1988 ACM Symposium on Lisp and + Functional Programming, pages 86–95. + +
  • [howtoprint] + +Robert G. Burger and R. Kent Dybvig. +Printing floating-point numbers quickly and accurately. +In Proceedings of the ACM SIGPLAN '96 Conference + on Programming Language Design and Implementation, pages 108–116. + +
  • [RRRS] + +William Clinger, editor. +The revised revised report on Scheme, or an uncommon Lisp. +MIT Artificial Intelligence Memo 848, August 1985. +Also published as Computer Science Department Technical Report 174, + Indiana University, June 1985. + +
  • [howtoread] +William Clinger. + +How to read floating point numbers accurately. +In Proceedings of the ACM SIGPLAN '90 Conference + on Programming Language Design and Implementation, pages 92–101. +Proceedings published as SIGPLAN Notices 25(6), June 1990. + +
  • [R4RS] + +William Clinger and Jonathan Rees, editors. +The revised^4 report on the algorithmic language Scheme. +In ACM Lisp Pointers 4(3), pages 1–55, 1991. + +
  • [macrosthatwork] +William Clinger and Jonathan Rees. + +Macros that work. +In Proceedings of the 1991 ACM Conference on Principles of + Programming Languages, pages 155–162. + +
  • [propertailrecursion] +William Clinger. + +Proper Tail Recursion and Space Efficiency. +To appear in Proceedings of the 1998 ACM Conference on Programming + Language Design and Implementation, June 1998. + +
  • [syntacticabstraction] + +R. Kent Dybvig, Robert Hieb, and Carl Bruggeman. +Syntactic abstraction in Scheme. +Lisp and Symbolic Computation 5(4):295–326, 1993. + +
  • [Scheme311] + +Carol Fessenden, William Clinger, Daniel P. Friedman, and Christopher Haynes. +Scheme 311 version 4 reference manual. +Indiana University Computer Science Technical Report 137, February 1983. +Superseded by [Scheme84]. + +
  • [Scheme84] + +D. Friedman, C. Haynes, E. Kohlbecker, and M. Wand. +Scheme 84 interim reference manual. +Indiana University Computer Science Technical Report 153, January 1985. + +
  • [IEEE] + +IEEE Standard 754-1985. IEEE Standard for Binary Floating-Point +Arithmetic. IEEE, New York, 1985. + +
  • [IEEEScheme] + +IEEE Standard 1178-1990. IEEE Standard for the Scheme + Programming Language. IEEE, New York, 1991. + +
  • [Kohlbecker86] + +Eugene E. Kohlbecker Jr. +Syntactic Extensions in the Programming Language Lisp. +PhD thesis, Indiana University, August 1986. + +
  • [hygienic] + +Eugene E. Kohlbecker Jr., Daniel P. Friedman, Matthias Felleisen, and Bruce Duba. +Hygienic macro expansion. +In Proceedings of the 1986 ACM Conference on Lisp + and Functional Programming, pages 151–161. + +
  • [Landin65] + +Peter Landin. +A correspondence between Algol 60 and Church's lambda notation: Part I. +Communications of the ACM 8(2):89–101, February 1965. + +
  • [MITScheme] + +MIT Department of Electrical Engineering and Computer Science. +Scheme manual, seventh edition. +September 1984. + +
  • [Naur63] + +Peter Naur et al. +Revised report on the algorithmic language Algol 60. +Communications of the ACM 6(1):1–17, January 1963. + +
  • [Penfield81] + +Paul Penfield, Jr. +Principal values and branch cuts in complex APL. +In APL '81 Conference Proceedings, pages 248–256. +ACM SIGAPL, San Francisco, September 1981. +Proceedings published as APL Quote Quad 12(1), ACM, September 1981. + +
  • [Pitman83] + +Kent M. Pitman. +The revised MacLisp manual (Saturday evening edition). +MIT Laboratory for Computer Science Technical Report 295, May 1983. + +
  • [Rees82] + +Jonathan A. Rees and Norman I. Adams IV. +T: A dialect of Lisp or, lambda: The ultimate software tool. +In Conference Record of the 1982 ACM Symposium on Lisp and + Functional Programming, pages 114–122. + +
  • [Rees84] + +Jonathan A. Rees, Norman I. Adams IV, and James R. Meehan. +The T manual, fourth edition. +Yale University Computer Science Department, January 1984. + +
  • [R3RS] + +Jonathan Rees and William Clinger, editors. +The revised^3 report on the algorithmic language Scheme. +In ACM SIGPLAN Notices 21(12), pages 37–79, December 1986. + +
  • [Reynolds72] + +John Reynolds. +Definitional interpreters for higher order programming languages. +In ACM Conference Proceedings, pages 717–740. +ACM, + 1972. + +
  • [Scheme78] + +Guy Lewis Steele Jr. and Gerald Jay Sussman. +The revised report on Scheme, a dialect of Lisp. +MIT Artificial Intelligence Memo 452, January 1978. + +
  • [Rabbit] + +Guy Lewis Steele Jr. +Rabbit: a compiler for Scheme. +MIT Artificial Intelligence Laboratory Technical Report 474, May 1978. + +
  • [CLtL] + +Guy Lewis Steele Jr. +Common Lisp: The Language, second edition. +Digital Press, Burlington MA, 1990. + +
  • [Scheme75] + +Gerald Jay Sussman and Guy Lewis Steele Jr. +Scheme: an interpreter for extended lambda calculus. +MIT Artificial Intelligence Memo 349, December 1975. + +
  • [Stoy77] + +Joseph E. Stoy. +Denotational Semantics: The Scott-Strachey Approach to + Programming Language Theory. +MIT Press, Cambridge, 1977. + +
  • [TImanual85] + +Texas Instruments, Inc. +TI Scheme Language Reference Manual. +Preliminary version 1.0, November 1985. + +
+ + + + + + + + +
+ + + + + + + + + + + +
Back: BibliographyForward: Concepts   FastBack: BibliographyUp: Revised(5) Report on the Algorithmic Language SchemeFastForward: Alphabetic index of definitions of concepts, keywords, and proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ +

Alphabetic index of definitions of concepts, keywords, and procedures

+ + + +

The principal entry for each term, procedure, or keyword is listed +first, separated from the other entries by a semicolon. +

+
+
+
+
+
+
+ +
+ + + + + + + + + + + +
Back: Alphabetic index of definitions of concepts, keywords, and proceduresForward: Procedures   FastBack: Alphabetic index of definitions of concepts, keywords, and proceduresUp: Alphabetic index of definitions of concepts, keywords, and proceduresFastForward: Alphabetic index of definitions of concepts, keywords, and proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+

Concepts

+
Jump to:   ' +   +, +   +; +   += +   +` +   +
+B +   +C +   +D +   +E +   +F +   +H +   +I +   +K +   +L +   +M +   +N +   +O +   +P +   +R +   +S +   +T +   +U +   +V +   +W +   +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Index Entry Section

'
'4.1.2 Literal expressions

,
,4.2.6 Quasiquotation
,@4.2.6 Quasiquotation

;
;2.2 Whitespace and comments

=
=>4.2.1 Conditionals

`
4.2.6 Quasiquotation

B
backquote4.2.6 Quasiquotation
binding3.1 Variables; syntactic keywords; and regions
binding construct3.1 Variables; syntactic keywords; and regions
bound3.1 Variables; syntactic keywords; and regions

C
call4.1.3 Procedure calls
call by need4.2.5 Delayed evaluation
combination4.1.3 Procedure calls
comma4.2.6 Quasiquotation
comment2.2 Whitespace and comments
comment7.1.1 Lexical structure
constant3.4 Storage model
continuation6.4 Control features

D
define5.2 Definitions
define-syntax5.3 Syntax definitions
definition5.2 Definitions
do4.2.4 Iteration
dotted pair6.3.2 Pairs and lists

E
else4.2.1 Conditionals
empty list3.2 Disjointness of types
empty list6.3.1 Booleans
empty list6.3.2 Pairs and lists
empty list6.3.2 Pairs and lists
empty list6.3.2 Pairs and lists
empty list6.3.2 Pairs and lists
empty list6.3.2 Pairs and lists
equivalence predicate6.1 Equivalence predicates
error1.3.2 Error situations and unspecified behavior
escape procedure6.4 Control features
exact6.1 Equivalence predicates
exactness6.2.2 Exactness

F
false3.2 Disjointness of types
false6.3.1 Booleans
false6.3.1 Booleans

H
hygienic4.3 Macros

I
identifier2.1 Identifiers
identifier3.1 Variables; syntactic keywords; and regions
identifier6.3.3 Symbols
identifier7.1.1 Lexical structure
immutable3.4 Storage model
implementation restriction1.3.2 Error situations and unspecified behavior
implementation restriction6.2.3 Implementation restrictions
improper list6.3.2 Pairs and lists
inexact6.1 Equivalence predicates
initial environment6. Standard procedures
internal definition5.2.2 Internal definitions

K
keyword4.3 Macros
keyword4.3 Macros
keyword7.1.1 Lexical structure

L
lazy evaluation4.2.5 Delayed evaluation
library1.3.1 Primitive; library; and optional features
library procedure6. Standard procedures
location3.4 Storage model

M
macro4.3 Macros
macro keyword4.3 Macros
macro transformer4.3 Macros
macro use4.3 Macros
mutable3.4 Storage model

N
number6.2 Numbers
numerical types6.2.1 Numerical types

O
object1.1 Semantics
optional1.3.1 Primitive; library; and optional features

P
pair6.3.2 Pairs and lists
port6.6.1 Ports
predicate6.1 Equivalence predicates
procedure call4.1.3 Procedure calls
promise4.2.5 Delayed evaluation
promise6.4 Control features
proper tail recursion3.5 Proper tail recursion

R
referentially transparent4.3 Macros
region3.1 Variables; syntactic keywords; and regions
region4.1.6 Assignments
region4.2.2 Binding constructs
region4.2.2 Binding constructs
region4.2.2 Binding constructs
region4.2.2 Binding constructs
region4.2.4 Iteration

S
simplest rational6.2.5 Numerical operations
syntactic keyword2.1 Identifiers
syntactic keyword3.1 Variables; syntactic keywords; and regions
syntactic keyword4.3 Macros
syntactic keyword7.1.1 Lexical structure
syntax definition5.3 Syntax definitions

T
tail call3.5 Proper tail recursion
token7.1.1 Lexical structure
top level environment3.1 Variables; syntactic keywords; and regions
top level environment6. Standard procedures
true3.2 Disjointness of types
true4.1.5 Conditionals
true4.2.1 Conditionals
true6.3.1 Booleans
type3.2 Disjointness of types

U
unbound3.1 Variables; syntactic keywords; and regions
unbound4.1.1 Variable references
unbound5.2.1 Top level definitions
unspecified1.3.2 Error situations and unspecified behavior

V
valid indexes6.3.5 Strings
valid indexes6.3.6 Vectors
variable2.1 Identifiers
variable3.1 Variables; syntactic keywords; and regions
variable4.1.1 Variable references
variable7.1.1 Lexical structure

W
Whitespace2.2 Whitespace and comments

+
Jump to:   ' +   +, +   +; +   += +   +` +   +
+B +   +C +   +D +   +E +   +F +   +H +   +I +   +K +   +L +   +M +   +N +   +O +   +P +   +R +   +S +   +T +   +U +   +V +   +W +   +
+ +
+ + + + + + + + + + + +
Back: ConceptsForward: Procedures   FastBack: Alphabetic index of definitions of concepts, keywords, and proceduresUp: Alphabetic index of definitions of concepts, keywords, and proceduresFastForward: Alphabetic index of definitions of concepts, keywords, and proceduresTop: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+

Procedures

+
Jump to:   +   +' +   +* +   ++ +   +- +   +/ +   +< +   += +   +> +   +` +   +
+A +   +B +   +C +   +D +   +E +   +F +   +G +   +I +   +L +   +M +   +N +   +O +   +P +   +Q +   +R +   +S +   +T +   +V +   +W +   +Z +   +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Index Entry Section

6.3.2 Pairs and lists

'
'4.1.2 Literal expressions

*
*6.2.5 Numerical operations

+
+6.2.5 Numerical operations

-
-6.2.5 Numerical operations
-6.2.5 Numerical operations
-6.2.5 Numerical operations

/
/6.2.5 Numerical operations
/6.2.5 Numerical operations
/6.2.5 Numerical operations

<
<6.2.5 Numerical operations
<=6.2.5 Numerical operations

=
=6.2.5 Numerical operations

>
>6.2.5 Numerical operations
>=6.2.5 Numerical operations

`
`4.2.6 Quasiquotation

A
abs6.2.5 Numerical operations
acos6.2.5 Numerical operations
and4.2.1 Conditionals
angle6.2.5 Numerical operations
append6.3.2 Pairs and lists
apply6.4 Control features
asin6.2.5 Numerical operations
assoc6.3.2 Pairs and lists
assq6.3.2 Pairs and lists
assv6.3.2 Pairs and lists
atan6.2.5 Numerical operations
atan6.2.5 Numerical operations

B
begin4.2.3 Sequencing
boolean?6.3.1 Booleans

C
caar6.3.2 Pairs and lists
cadr6.3.2 Pairs and lists
call-with-current-continuation6.4 Control features
call-with-input-file6.6.1 Ports
call-with-output-file6.6.1 Ports
call-with-values6.4 Control features
car6.3.2 Pairs and lists
case4.2.1 Conditionals
cdddar6.3.2 Pairs and lists
cddddr6.3.2 Pairs and lists
cdr6.3.2 Pairs and lists
ceiling6.2.5 Numerical operations
char->integer6.3.4 Characters
char-alphabetic?6.3.4 Characters
char-ci<=?6.3.4 Characters
char-ci<?6.3.4 Characters
char-ci=?6.3.4 Characters
char-ci>=?6.3.4 Characters
char-ci>?6.3.4 Characters
char-downcase6.3.4 Characters
char-lower-case?6.3.4 Characters
char-numeric?6.3.4 Characters
char-ready?6.6.2 Input
char-ready?6.6.2 Input
char-upcase6.3.4 Characters
char-upper-case?6.3.4 Characters
char-whitespace?6.3.4 Characters
char<=?6.3.4 Characters
char<?6.3.4 Characters
char=?6.3.4 Characters
char>=?6.3.4 Characters
char>?6.3.4 Characters
char?6.3.4 Characters
close-input-port6.6.1 Ports
close-output-port6.6.1 Ports
complex?6.2.5 Numerical operations
cond4.2.1 Conditionals
cons6.3.2 Pairs and lists
cos6.2.5 Numerical operations
current-input-port6.6.1 Ports
current-output-port6.6.1 Ports

D
delay4.2.5 Delayed evaluation
denominator6.2.5 Numerical operations
display6.6.3 Output
display6.6.3 Output
do4.2.4 Iteration
dynamic-wind6.4 Control features

E
eof-object?6.6.2 Input
eq?6.1 Equivalence predicates
equal?6.1 Equivalence predicates
eqv?6.1 Equivalence predicates
eval6.5 Eval
even?6.2.5 Numerical operations
exact->inexact6.2.5 Numerical operations
exact?6.2.5 Numerical operations
exp6.2.5 Numerical operations
expt6.2.5 Numerical operations

F
floor6.2.5 Numerical operations
for-each6.4 Control features
force6.4 Control features

G
gcd6.2.5 Numerical operations

I
if4.1.5 Conditionals
if4.1.5 Conditionals
imag-part6.2.5 Numerical operations
inexact->exact6.2.5 Numerical operations
inexact?6.2.5 Numerical operations
input-port?6.6.1 Ports
integer->char6.3.4 Characters
integer?6.2.5 Numerical operations
interaction-environment6.5 Eval

L
lambda4.1.4 Procedures
lcm6.2.5 Numerical operations
length6.3.2 Pairs and lists
let4.2.2 Binding constructs
let4.2.4 Iteration
let*4.2.2 Binding constructs
let-syntax4.3.1 Binding constructs for syntactic keywords
letrec4.2.2 Binding constructs
letrec-syntax4.3.1 Binding constructs for syntactic keywords
list6.3.2 Pairs and lists
list->string6.3.5 Strings
list->vector6.3.6 Vectors
list-ref6.3.2 Pairs and lists
list-tail6.3.2 Pairs and lists
list?6.3.2 Pairs and lists
load6.6.4 System interface
log6.2.5 Numerical operations

M
magnitude6.2.5 Numerical operations
make-polar6.2.5 Numerical operations
make-rectangular6.2.5 Numerical operations
make-string6.3.5 Strings
make-string6.3.5 Strings
make-vector6.3.6 Vectors
make-vector6.3.6 Vectors
map6.4 Control features
max6.2.5 Numerical operations
member6.3.2 Pairs and lists
memq6.3.2 Pairs and lists
memv6.3.2 Pairs and lists
min6.2.5 Numerical operations
modulo6.2.5 Numerical operations

N
negative?6.2.5 Numerical operations
newline6.6.3 Output
newline6.6.3 Output
not6.3.1 Booleans
null-environment6.5 Eval
null?6.3.2 Pairs and lists
number->string6.2.6 Numerical input and output
number->string6.2.6 Numerical input and output
number?6.2.5 Numerical operations
numerator6.2.5 Numerical operations

O
odd?6.2.5 Numerical operations
open-input-file6.6.1 Ports
open-output-file6.6.1 Ports
or4.2.1 Conditionals
output-port?6.6.1 Ports

P
pair?6.3.2 Pairs and lists
peek-char6.6.2 Input
peek-char6.6.2 Input
positive?6.2.5 Numerical operations
procedure?6.4 Control features

Q
quasiquote4.2.6 Quasiquotation
quote4.1.2 Literal expressions
quotient6.2.5 Numerical operations

R
rational?6.2.5 Numerical operations
rationalize6.2.5 Numerical operations
read6.6.2 Input
read6.6.2 Input
read-char6.6.2 Input
read-char6.6.2 Input
real-part6.2.5 Numerical operations
real?6.2.5 Numerical operations
remainder6.2.5 Numerical operations
reverse6.3.2 Pairs and lists
round6.2.5 Numerical operations

S
scheme-report-environment6.5 Eval
set!4.1.6 Assignments
set-car!6.3.2 Pairs and lists
set-cdr!6.3.2 Pairs and lists
sin6.2.5 Numerical operations
sqrt6.2.5 Numerical operations
string6.3.5 Strings
string->list6.3.5 Strings
string->number6.2.6 Numerical input and output
string->number6.2.6 Numerical input and output
string->symbol6.3.3 Symbols
string-append6.3.5 Strings
string-ci<=?6.3.5 Strings
string-ci<?6.3.5 Strings
string-ci=?6.3.5 Strings
string-ci>=?6.3.5 Strings
string-ci>?6.3.5 Strings
string-copy6.3.5 Strings
string-fill!6.3.5 Strings
string-length6.3.5 Strings
string-ref6.3.5 Strings
string-set!6.3.5 Strings
string<=?6.3.5 Strings
string<?6.3.5 Strings
string=?6.3.5 Strings
string>=?6.3.5 Strings
string>?6.3.5 Strings
string?6.3.5 Strings
substring6.3.5 Strings
symbol->string6.3.3 Symbols
symbol?6.3.3 Symbols
syntax-rules4.3.2 Pattern language

T
tan6.2.5 Numerical operations
transcript-off6.6.4 System interface
transcript-on6.6.4 System interface
truncate6.2.5 Numerical operations

V
values6.4 Control features
vector6.3.6 Vectors
vector->list6.3.6 Vectors
vector-fill!6.3.6 Vectors
vector-length6.3.6 Vectors
vector-ref1.3.3 Entry format
vector-ref6.3.6 Vectors
vector-set!6.3.6 Vectors
vector?6.3.6 Vectors

W
with-input-from-file6.6.1 Ports
with-output-to-file6.6.1 Ports
write6.6.3 Output
write6.6.3 Output
write-char6.6.3 Output
write-char6.6.3 Output

Z
zero?6.2.5 Numerical operations

+
Jump to:   +   +' +   +* +   ++ +   +- +   +/ +   +< +   += +   +> +   +` +   +
+A +   +B +   +C +   +D +   +E +   +F +   +G +   +I +   +L +   +M +   +N +   +O +   +P +   +Q +   +R +   +S +   +T +   +V +   +W +   +Z +   +
+ + + +
+ + + + + +
Top: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+

Table of Contents

+
+ + +
+
+ + + + + +
Top: Revised(5) Report on the Algorithmic Language SchemeContents: Table of ContentsIndex: Alphabetic index of definitions of concepts, keywords, and procedures
+ + + diff --git a/examples/iOS/r5rs.pdf b/examples/iOS/r5rs.pdf new file mode 100644 index 000000000..ae7a394e6 Binary files /dev/null and b/examples/iOS/r5rs.pdf differ diff --git a/examples/iOS/repl-server#.scm b/examples/iOS/repl-server#.scm new file mode 100644 index 000000000..8f19dc4c4 --- /dev/null +++ b/examples/iOS/repl-server#.scm @@ -0,0 +1,15 @@ +;;;============================================================================ + +;;; File: "repl-server#.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("repl-server#" + +repl-server-start + +)) + +;;;============================================================================ diff --git a/examples/iOS/repl-server.scm b/examples/iOS/repl-server.scm new file mode 100644 index 000000000..01539d261 --- /dev/null +++ b/examples/iOS/repl-server.scm @@ -0,0 +1,155 @@ +;;;============================================================================ + +;;; File: "repl-server.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("repl-server#")) + +(##include "~~lib/gambit#.scm") + +(##include "repl-server#.scm") + +(declare + (standard-bindings) + (extended-bindings) + (block) + (fixnum) + ;;(not safe) +) + + +;;;============================================================================ + +;; REPL server which can be contacted via telnet on port 7000. + +(define (ide-repl-pump ide-repl-connection in-port out-port tgroup) + + (define m (make-mutex)) + + (define (process-input) + (let loop ((state 'normal)) + (let ((c (read-char ide-repl-connection))) + (if (not (eof-object? c)) + (case state + ((normal) + (if (char=? c #\xff) ;; telnet IAC (interpret as command) code? + (loop c) + (begin + (mutex-lock! m) + (if (char=? c #\x04) ;; ctrl-d ? + (close-output-port out-port) + (begin + (write-char c out-port) + (force-output out-port))) + (mutex-unlock! m) + (loop state)))) + ((#\xfb) ;; after WILL command? + (loop 'normal)) + ((#\xfc) ;; after WONT command? + (loop 'normal)) + ((#\xfd) ;; after DO command? + (if (char=? c #\x06) ;; timing-mark option? + (begin ;; send back WILL timing-mark + (mutex-lock! m) + (write-char #\xff ide-repl-connection) + (write-char #\xfb ide-repl-connection) + (write-char #\x06 ide-repl-connection) + (force-output ide-repl-connection) + (mutex-unlock! m))) + (loop 'normal)) + ((#\xfe) ;; after DONT command? + (loop 'normal)) + ((#\xff) ;; after IAC command? + (case c + ((#\xf4) ;; telnet IP (interrupt process) command? + (for-each + ##thread-interrupt! + (thread-group->thread-list tgroup)) + (loop 'normal)) + ((#\xfb #\xfc #\xfd #\xfe) ;; telnet WILL/WONT/DO/DONT command? + (loop c)) + (else + (loop 'normal)))) + (else + (loop 'normal))))))) + + (define (process-output) + (let loop () + (let ((c (read-char in-port))) + (if (not (eof-object? c)) + (begin + (mutex-lock! m) + (write-char c ide-repl-connection) + (force-output ide-repl-connection) + (mutex-unlock! m) + (loop)))))) + + (let ((tgroup (make-thread-group 'repl-pump #f))) + (thread-start! (make-thread process-input #f tgroup)) + (thread-start! (make-thread process-output #f tgroup)))) + +(define (make-ide-repl-ports ide-repl-connection tgroup) + (receive (in-rd-port in-wr-port) (open-string-pipe '(direction: input permanent-close: #f)) + (receive (out-wr-port out-rd-port) (open-string-pipe '(direction: output)) + (begin + + ;; Hack... set the names of the ports for usage with gambit.el + (##vector-set! in-rd-port 4 (lambda (port) '(stdin))) + (##vector-set! out-wr-port 4 (lambda (port) '(stdout))) + + (ide-repl-pump ide-repl-connection out-rd-port in-wr-port tgroup) + (values in-rd-port out-wr-port))))) + +(define repl-channel-table (make-table test: eq?)) + +(set! ##thread-make-repl-channel + (lambda (thread) + (let ((tgroup (thread-thread-group thread))) + (or (table-ref repl-channel-table tgroup #f) + (##default-thread-make-repl-channel thread))))) + +(define (setup-ide-repl-channel ide-repl-connection tgroup) + (receive (in-port out-port) (make-ide-repl-ports ide-repl-connection tgroup) + (let ((repl-channel (##make-repl-channel-ports in-port out-port))) + (table-set! repl-channel-table tgroup repl-channel)))) + +(define repl-server-address #f) +(set! repl-server-address "*:7000") + +(define (repl-server password) + (let ((server + (open-tcp-server + (list server-address: repl-server-address + eol-encoding: 'cr-lf + reuse-address: #t)))) + (let loop1 () + (let* ((ide-repl-connection + (read server)) + (tgroup + (make-thread-group 'repl-service #f)) + (thread + (make-thread + (lambda () + (setup-ide-repl-channel ide-repl-connection tgroup) + (if password + (let loop2 () + (display "Password: " ide-repl-connection) + (force-output ide-repl-connection) + (let ((pw (read-line ide-repl-connection))) + (if (not (equal? pw password)) + (loop2))))) + (##repl-debug-main)) + 'repl + tgroup))) + (thread-start! thread) + (loop1))))) + +(define (repl-server-start password) + (thread-start! (make-thread (lambda () (repl-server password)))) + (void)) + + +;;;============================================================================ diff --git a/examples/iOS/repo#.scm b/examples/iOS/repo#.scm new file mode 100644 index 000000000..3447be477 --- /dev/null +++ b/examples/iOS/repo#.scm @@ -0,0 +1,18 @@ +;;;============================================================================ + +;;; File: "repo#.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("repo#" + +reset-login-info +set-login-info +get-login-info +save-login-info + +)) + +;;;============================================================================ diff --git a/examples/iOS/repo.scm b/examples/iOS/repo.scm new file mode 100644 index 000000000..c45516ff0 --- /dev/null +++ b/examples/iOS/repo.scm @@ -0,0 +1,71 @@ +;;;============================================================================ + +;;; File: "repo.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("repo#")) + +(##include "~~lib/gambit#.scm") + +(##include "repo#.scm") +(##include "intf#.scm") + +(declare + (standard-bindings) + (extended-bindings) + (block) + (fixnum) + ;;(not safe) +) + + +;;;============================================================================ + +;; Login info. + +(define predefined-login-info '("" "" #t)) + +(define login-info #f) +(define login-info-version "1.0") + +(define (reset-login-info) + (let ((info (get-login-info))) + (set-login-info "" "" (caddr info)) + (save-login-info))) + +(define (set-login-info username password remember-pass?) + (set! login-info + (list username + (if remember-pass? password "") + remember-pass?))) + +(define (get-login-info) + (if (not login-info) + (set! login-info + (let ((x (get-pref "login-info"))) + (if x + (let ((lst (with-input-from-string x read))) + (if (pair? lst) + (let ((version (car lst)) + (info (cdr lst))) + (cond ((equal? version login-info-version) + info) + (else + predefined-login-info))) + predefined-login-info)) + predefined-login-info)))) + login-info) + +(define (save-login-info) + (if login-info + (set-pref "login-info" + (with-output-to-string + "" + (lambda () + (write (cons login-info-version login-info))))))) + + +;;;============================================================================ diff --git a/examples/iOS/script#.scm b/examples/iOS/script#.scm new file mode 100644 index 000000000..cc1ffcb41 --- /dev/null +++ b/examples/iOS/script#.scm @@ -0,0 +1,27 @@ +;;;============================================================================ + +;;; File: "script#.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("script#" + +predefined-scripts +script-db +script-db-version +reset-scripts +get-script-by-name +get-script-index-by-name +get-script-at-index +get-script-db +new-script +add-script name +save-script-db +load-script +run-script + +)) + +;;;============================================================================ diff --git a/examples/iOS/script.scm b/examples/iOS/script.scm new file mode 100644 index 000000000..b3328ab11 --- /dev/null +++ b/examples/iOS/script.scm @@ -0,0 +1,175 @@ +;;;============================================================================ + +;;; File: "script.scm" + +;;; Copyright (c) 2011 by Marc Feeley, All Rights Reserved. + +;;;============================================================================ + +(##namespace ("script#")) + +(##include "~~lib/gambit#.scm") +(##include "~~lib/_gambit#.scm") + +(##include "script#.scm") +(##include "intf#.scm") + +(declare + (standard-bindings) + (extended-bindings) + (block) + (fixnum) + (not safe) +) + +;;;============================================================================ + +;; Script database operations. + +(define predefined-scripts '( + +("fact100" . +#<list revision1)))) content)))))) -(define (mediawiki-page-delete timeout server-address docu session title) +(define (mediawiki-page-remove timeout server-address docu session title) (let* ((x (mediawiki-action timeout @@ -419,10 +419,10 @@ (let ((source-text (substring text tag1-len (- len tag2-len)))) source-text))))) -(define (wiki-script-delete script-name) +(define (wiki-script-remove script-name) (wiki-script-name-verify script-name) (wiki-logged-in-verify) - (mediawiki-page-delete + (mediawiki-page-remove wiki-timeout wiki-server-address (string-append wiki-root wiki-api) @@ -437,25 +437,54 @@ (raise "you must first login to the Gambit wiki"))) (define (wiki-script-name-verify script-name) + (if (not (eq? (wiki-script-name-type script-name) 'wiki)) + (raise "illegal wiki script name"))) + +(define (wiki-script-name-type script-name) (if (not (string? script-name)) - (raise "script name must be a string") + #f (let ((len (string-length script-name))) - (if (or (< len 4) - (not (string=? ".scm" (substring script-name (- len 4) len)))) - (raise "script name must end with \".scm\"") - (let ((x (string->list script-name))) - (cond ((not (and (char>=? (car x) #\A) (char<=? (car x) #\Z))) - (raise "script name must start with an upper case letter")) - ((not (memv #\: x)) - (raise "script name must contain at least one colon")) - (else - (for-each - (lambda (c) - (if (not (or (and (char>=? c #\a) (char<=? c #\z)) - (and (char>=? c #\A) (char<=? c #\Z)) - (and (char>=? c #\0) (char<=? c #\9)) - (memv c '(#\space #\- #\. #\:)))) - (raise "illegal character in script name"))) - x)))))))) + (if (= len 0) + #f + (let ((has-scm-ext? #f) + (has-colon? #f) + (has-space? #f)) + (let loop ((i (- (if (or (< len 4) + (not (string=? ".scm" + (substring script-name (- len 4) len)))) + len + (begin + (set! has-scm-ext? #t) + (- len 4))) + 1))) + (if (< i 0) + (cond ((and has-scm-ext? + has-colon? + (let ((c (string-ref script-name 0))) + (and (char>=? c #\A) (char<=? c #\Z)))) + 'wiki) + ((and has-scm-ext? + (not has-colon?) + (not has-space?)) + 'file) + ((not has-space?) + 'script) + (else + #f)) + (let ((c (string-ref script-name i))) + (cond ((char=? c #\:) + (set! has-colon? #t) + (loop (- i 1))) + ((char=? c #\space) + (set! has-space? #t) + (loop (- i 1))) + ((or (and (char>=? c #\a) (char<=? c #\z)) + (and (char>=? c #\A) (char<=? c #\Z)) + (and (char>=? c #\0) (char<=? c #\9)) + (memv c '(#\- #\.))) + (loop (- i 1))) + (else + #f)))))))))) + ;;;============================================================================ diff --git a/include/gambit.h.in b/include/gambit.h.in index 40fa5943f..c364fc707 100644 --- a/include/gambit.h.in +++ b/include/gambit.h.in @@ -1,4 +1,4 @@ -/* File: "gambit.h", Time-stamp: <2011-04-26 09:17:04 feeley> */ +/* File: "gambit.h" */ /* * Copyright (c) 1994-2011 by Marc Feeley, All Rights Reserved. @@ -1210,6 +1210,9 @@ #endif #else #ifndef ___NOT_USE_LABEL_VALUES +#ifdef __llvm__ +#define ___NOT_USE_LABEL_VALUES +#else #ifdef __GNUC__ #define ___USE_LABEL_VALUES #else @@ -1217,6 +1220,7 @@ #endif #endif #endif +#endif /*---------------------------------------------------------------------------*/ diff --git a/makefile.in b/makefile.in index 80980e07b..5a2f4a7df 100644 --- a/makefile.in +++ b/makefile.in @@ -76,7 +76,7 @@ RCFILES = README INSTALL.txt LICENSE-2.0.txt LGPL.txt \ makefile.in configure configure.ac config.guess config.sub install-sh mkidirs \ relpath -GITRCFILES = .gitignore +GITRCFILES = .gitignore .gitattributes HGRCFILES = .hgignore .hgtags GENDISTFILES =