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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Patrick M Doane <patrick@w...>
Subject: Re: [Caml-list] Random results
Hi Markus,

You have an interesting problem in the code that is hard to spot at first.
I'll interleave some comments below:

On Sat, 21 Apr 2001, markus.kliegl wrote:

> let rot13_char c =
>   let x = int_of_char c in
>     if (x >= 65 && x < 78) || (x >= 97 && x < 110) then
>       char_of_int (x + 13)
>     else if (x >= 78 && x < 91) || (x >= 110 && x < 123) then
>       char_of_int (x - 13)
>     else c
> ;;

Note that rot13_char (rot13_char c) == c

> let rot13_str str =
>   for i = 0 to String.length str - 1 do
>     str.[i] <- (rot13_char str.[i])
>   done;
>   str
> ;;

String updates in Caml are destructive, and strings are passed "by
reference" to use C++ terminology.  So this means that: 

  (rot13_str s) == s

which may not be expected.

> let rec beer n =
>   if n = 1 then begin
>     rot_print "1 bottle of beer on the wall";
>     rot_print "1 bottle of beer";
>     rot_print "Take one down and pass it around";
>     rot_print "No bottles of beer on the wall"
>   end else begin
>     print_int n; rot_print " bottles of beer on the wall";
>     print_int n; rot_print " bottles of beer";
>     rot_print "Take one down and pass it around";
>     print_int (n - 1); rot_print " bottles of beer on the wall";
>     print_newline ();
>     beer (n - 1)
>   end
> ;;

Since rot13_str destructively modifies its argument, the string literals
are getting modified. Each invokation of beer for n > 2 will alternate
between rot13 and plaintext representation. 

Patrick Doane

-------------------
To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr