This is probably a question of personal taste, but I would
not use l as a variable name when I optimize for
readability. If performance is not critical I'd just make a
list with all of them.
let cons h t = h :: t;;
let rec comb n k =
match (n, k) with
(0, 0) -> [[]]
| (0, _) -> []
| (_, _) ->
List.rev_append
(List.map (cons (n-1)) (comb (n-1) (k-1)))
(comb (n-1) k);;
----- Original Message ----
From: roparzhhemon <roparzhhemon yahoo.com.br>
To: ocaml_beginners@yahoogroups.com
Sent: Sunday, November 12, 2006 1:03:44 PM
Subject: "ocaml_beginners"::[] Re: Generate the
combinations of K distinct objects chosen from an N-element
list
--- In ocaml_beginners@yahoogroups.com, "Ulrich"
<ulrivo ...> wrote:
>
> But this is not so beauty and readable as the Prolog
solution:
Well, maybe you think that because you're new to ocaml.
Your
"next_vect" function looks quite readable and
short to me.
here's how I would do it (without having to define a new
type) :
let rec combinations k l=
if k=0 then [[]] else
if List.length(l)<k then [] else
let head=List.hd(l) and tail=List.tl(l) in
let first_part_of_answer=List.map(function
y->head::y)(combinations (k-1) tail)
and second_part_of_answer=combinations(k)(tail) in
first_part_of_answer second_part_of_answer
This code optimizes readibility, not performance.
Hope this helps ...
Ewan
Archives up to November 11, 2006 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
Archives up to November 11, 2006 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
<*> To visit your group on the web, go to:
http:/
/groups.yahoo.com/group/ocaml_beginners/
<*> Your email settings:
Individual Email | Traditional
<*> To change settings online go to:
ht
tp://groups.yahoo.com/group/ocaml_beginners/join
(Yahoo! ID required)
<*> To change settings via email:
mailto:ocaml_beginners-digest@yahoogroups.com
mailto:ocaml_beginners-fullfeatured@yahoogroups.com
<*> To unsubscribe from this group, send an email to:
ocaml_beginners-unsubscribe@yahoogroups.com
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.c
om/info/terms/
|