English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

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: 2006-03-14 (08:57)
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
   close_out chan;

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.