Hello,
as I am learning Ocaml, I solved some of the 99 Prolog Problems at
http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/
<http://www.hta-bi.bfh.ch/%7Ehew/informatik3/prolog/p-99/>
Looking at problem 26 "Generate the combinations of K distinct objects
chosen from the N elements of a list", I do not like my Ocaml solution.
I define the type
type 'a combination = { liste : 'a list; vector : int list}
where the vector contains the indices which point into the liste. Then I
increment the vector to generate the next combination
exception No_increment
let rec next_vector li n = match li with
[] -> raise No_increment
| x :: r -> if x<n-1 then (x+1) :: r else
let next_vec = next_vector r (n-1) in
((List.hd next_vec) +1) :: next_vec
But this is not so beauty and readable as the Prolog solution:
el(X,[X|L],L).
el(X,[_|L],R) :- el(X,L,R).
combination(0,_,[]).
combination(K,L,[X|Xs]) :- K > 0,
el(X,L,R),
K1 is K-1,
combination(K1,R,Xs).
Has anybody a nicer idea to find all combinations with Ocaml?
How do I generate or backtrack?
Regards,
Ulrich
[Non-text portions of this message have been removed]
.