Comma quibbling: Difference between revisions

Content deleted Content added
Chunes (talk | contribs)
added a solution for Factor
add OCaml
Line 2,299:
$ bin/CommaQuibbling ABC DEF G H
:> {ABC, DEF, G and H}
</pre>
 
=={{header|OCaml}}==
 
<lang ocaml>open Printf
 
let quibble list =
let rec aux = function
| a :: b :: c :: d :: rest -> a ^ ", " ^ aux (b :: c :: d :: rest)
| [a; b; c] -> sprintf "%s, %s and %s}" a b c
| [a; b] -> sprintf "%s and %s}" a b
| [a] -> sprintf "%s}" a
| [] -> "}" in
"{" ^ aux list
 
let test () =
[[];
["ABC"];
["ABC"; "DEF"];
["ABC"; "DEF"; "G"; "H"]]
|> List.iter (fun list -> print_endline (quibble list))</lang>
 
{{works with|Core|v0.9.116.03+91}}
<lang ocaml>open Core
 
let quibble = function
| [| |] -> "{}"
| [| a |] -> sprintf "{%s}" a
| array ->
let last, rest = Array.last array, Array.slice array 0 (-1) in
sprintf "{%s and %s}" (String.concat_array ~sep:", " rest) last
 
let test () =
[[||];
[|"ABC"|];
[|"ABC"; "DEF"|];
[|"ABC"; "DEF"; "G"; "H"|]]
|> List.iter ~f:(fun list -> print_endline (quibble list))</lang>
 
{{out}}
<pre># test ();;
{}
{ABC}
{ABC and DEF}
{ABC, DEF, G and H}
</pre>