Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: [Caml-list] OCaml compared as a scripting language
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: sejourne kevin <sejourne_kevin@y...>
Subject: Re: [Caml-list] OCaml compared as a scripting language
--- Brian Hurt <bhurt@spnz.org> a écrit : > On Tue, 15
Jun 2004, Hellflame wrote:
> An example of this is implicit sideeffects
> side-effects- something Perl 
> does a lot of.  This is actually an efficiency in
> the small, and it lets 
> you write quick hacks like (if I recall my Perl
> correctly):
> 	while (<>) {
> 		$count += $_;
> 	}
> 
> The equivelent Ocaml code might look something like:
> 
> let sumfile =
> 	let rec loop cnt =
> 		let line, eof =
> 			try
> 				(input_line stdin), false
> 			with
> 				| End_of_file -> "", true
> 		in
> 		if eof then
> 			cnt
> 		else
> 			loop (cnt + (int_of_string line))
> 	in
> 	loop 0
> ;;
> 
> I just quintupled the lines of code there- 3 lines
> to 15 lines.  
> 
> But the problem is that Perl get's in brevity (in
> part) by sideeffects- it 
> sets the (effectively) global and widely used $_
> variable.  If the code 
> got modified to:
> 	while (<>) {
> 		do_something(1, 2, 3);
> 		$count += $_;
> 	}
files can be see as a kind of data for an iterator.
In my personnals libs I have function like :
let fold_lefti f x a =
  let r = ref x in
  for i = 0 to Array.length a - 1 do
    r := f  i !r  a.(i)
  done;
  !r
;;

let file_fold_left fonction result file =
  let r = ref result in
   try while true do r:= fonction !r file done; !r
   with | End_of_file -> !r
;;

...

For the sum I use the second:

 let sumfile name = 
  let cin = open_in name in
  let result =
    file_fold_left (fun r
f->r+int_of_string(input_line f)) 0 cin
  in close_in cin;
    result
;;

and for stdin :

let sumstdin =
  file_fold_left (fun r _->r+(int_of_string
(read_line()) ) ) 0 ()
;;


So if I use my libs ( :-) ) then for the sum in write
only 3 lines too.

kevin


	

	
		
Yahoo! Mail : votre e-mail personnel et gratuit qui vous suit partout ! 
Créez votre Yahoo! Mail sur http://fr.benefits.yahoo.com/

Dialoguez en direct avec vos amis grâce à Yahoo! Messenger !Téléchargez Yahoo! Messenger sur http://fr.messenger.yahoo.com

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners