home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Moscow ML 1.42 / examples / mls / mls.sml < prev   
Encoding:
Text File  |  1997-08-18  |  1.4 KB  |  43 lines  |  [TEXT/R*ch]

  1. (* A very simple version of the Unix utility ls: list directory. *)
  2.  
  3. fun listdir path = 
  4.     let open FileSys TextIO
  5.     val dir = openDir path
  6.     fun read "" res = res
  7.       | read f  res = read (readDir dir) (f :: res)
  8.     val filenames = Listsort.sort String.compare
  9.                     (read (readDir dir) []) before closeDir dir 
  10.     val (longest, count) = 
  11.         foldl (fn (x, (max, cnt)) => (Int.max(max, size x), cnt+1))
  12.               (0, 0) filenames
  13.         val cols = Int.max(1, 80 div (longest + 2));
  14.     val fstrows = (count-1) div cols
  15.     val lastrow = count - cols * fstrows       (* 0 <= lastrow <= cols *)
  16.  
  17.     val filenames = Vector.fromList filenames        
  18.     fun file (row, col) = 
  19.         Vector.sub(filenames, col*fstrows+Int.min(lastrow, col)+row)
  20.     fun left n s = StringCvt.padRight #" " n s
  21.     fun prrow row j m = 
  22.         if j >= m then ""
  23.         else left (longest + 2) (file (row, j)) ^ prrow row (j+1) m
  24.     fun println s = output(stdOut, s ^ "\n")
  25.     fun prrows i = 
  26.         if i >= fstrows then () 
  27.         else (println (prrow i 0 cols); prrows (i+1))
  28.     in
  29.     prrows 0;                (* Print all rows but the last *)
  30.     println (prrow fstrows 0 lastrow)  (* Print the last row *)
  31.     end;
  32.  
  33. fun errmsg s = TextIO.output(TextIO.stdErr, s ^ "\n");
  34.  
  35. val _ = 
  36.     case Mosml.argv () of 
  37.     [_]      => listdir "."
  38.       | [_, dir] => ((listdir dir) 
  39.                 handle OS.SysErr (explanation, _) => 
  40.             errmsg ("Error: "^ explanation))
  41.       | _        => errmsg "Usage: mls [directory]"
  42.  
  43.