Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: [Caml-list] Hello
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: yoann padioleau <padator@w...>
Subject: Re: [Caml-list] Hello

> 
> > print_string "What's your name ? "; let name = read_line () in Printf.printf
> > "Hello, %s.\n" name ;;
> 
> let o = open_out "filename";;
> output_string o name;;
> close_out o;;

A better (advanced) way is to do it the Lisp way: 

with_open_outfile "filename" (fun chan -> 
  output_string chan name
 );


where with_open_outfile is defined by:

let with_open_outfile filename f = 
 let chan = open_out filename in
 let res = f chan in
 begin
   close_out chan;
   res
 end

Everywhere where 2 functions must be balanced (here open and close), it is cleaner to introduce
a single higher-order function to enforce such a protocol.

You can also use a function  unwind_protect (again invented by the Lisp folk I think)
to  also automagically close the channel when  f raise an exception.