Nitpicking (or as a morning coding exercise), the second solution is
quadratic in runtime and memory, as accumulating the result involves
string concatenation (a^b has O(length(a)+length(b)) space and time
complexity). Your first imperative solution is better from this point
I have a solution that is equivalent to your imperative one, less
clever (no attempt to "print all parenthesis at once"), and having the
defect of not being tail-rec:
let print_tuple out li =
let rec print_rev_tuple ~parens out = function
|  -> invalid_arg "print_tuple"
| [x] -> output_string out x
| x::xs ->
Printf.(if parens then fprintf out "(%a * %s)" else fprintf out "%a * %s")
(print_rev_tuple ~parens:true) xs x in
print_rev_tuple ~parens:false out (List.rev li)
(* prints "((a * b) * c) * d" *)
let () =
print_tuple stdout ["a"; "b"; "c"; "d"]
The ~parens parameter is really a state accumulator; one could use it
for funky things, such as printing a different kind of bracket for
each recursion depth.
This version prints to an out_channel. If one wish to get the result
as a change, just replace all "fprintf" by "bprintf" (and
output_string by Buffer.add_string) to print to a buffer instead.
On Thu, Mar 29, 2012 at 7:52 AM, Dan Bensen <danbensen@...> wrote:
>> for n = 0 to List.length xs do print_char '(' done;
>> # print ["'a"; "'b"; "'c"; "'d"];;
>> (((('a * 'b) * 'c) * 'd)
> Oops! Better make that "n = 1".
> Maybe functional code would be safer :)
> # let to_string = function
> |  -> "unit"
> | [x] -> x
> | x::xs -> List.fold_left (Printf.sprintf "(%s * %s)") x xs;;
> val to_string : string list -> string = <fun>
> # to_string ["'a"; "'b"; "'c"; "'d"];;
> - : string = "((('a * 'b) * 'c) * 'd)"
> [Non-text portions of this message have been removed]
> Archives up to December 31, 2011 are also downloadable at http://www.connettivo.net/cntprojects/ocaml_beginners
> The archives of the very official ocaml list (the seniors' one) can be found at http://caml.inria.fr
> Attachments are banned and you're asked to be polite, avoid flames etc.Yahoo! Groups Links