PreviousUpNext

14.2.44  Safely

The standard library Safely api defines access to functionality for handling exceptions encountered during the course of a subcomputation.

The Safely api is implemented by the safely package.

The Safely api source code is in src/lib/std/safely.pkg.

The above information is manually maintained and may contain errors.

api {
    do : {cleanup:Bool -> Void, close_it:X -> Void, open_it:Void -> X} -> (X -> Y) -> Y;};

The following information is manually maintained and may contain errors. A typical application of Safely is to catch I/O exceptions encountered during file I/O, close any open file descriptors, and continue execution appropriately:

    # Return an alphabetically sorted list of directory entries,
    # e.g. [ "bar", "foo", "zot" ], skipping those starting with a dot:
    #
    fun file_names (directory_name: String)
        =
        file_list
        where

            # Collect everything in directory
            # as a list of strings:
            #
            file_list
                =
                safely::do
                    {
                      open_it  =>  {. f::open_directory_stream  directory_name; },
                      close_it =>     f::close_directory_stream,
                      cleanup  =>     \\ _ =  ()
                    }
                   {.   loop []
                        where
                            fun loop results
                                =
                                case (f::read_directory_entry  #directory_stream)
                                  
                                     NULL
                                         =>
                                         list_mergesort::sort  string::(>)  results;

                                     THE filename
                                         =>
                                         # Ignore everything but vanilla files:
                                         #
                                         if   (is_file filename)   loop (filename ! results);
                                         else                      loop results;
                                         fi;
                                esac;
                        end;
                    };

        end;

This example processes a directory. The open_it thunk is called before first execution of the main loop, the close_it thunk will be called at the end, and the cleanup thunk argument provides an opportunity to do special recovery in case of an exception.

The main body thunk is called with the result of the open_it call, which in this case is #directory_stream.

This example is taken from src/lib/src/dir.pkg, which contains a number of additional examples.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext