prolog - Generating subsets using length/2 and ord_subset/2 -


i beginner in prolog. tried in swipl interpreter:

?- length(lists, 3), ord_subset(lists, [1, 2, 3, 4]). false. 

expecting length-3 lists subsets of [1, 2, 3, 4] [1, 2, 3] or [1, 2, 4]. why false?

notice: both length , ord_subset builtin functions (or whatever called) in swi-prolog.

you don't solution because ord_subset/2 predicate checks if list subset of list; not generate subsets.

here 1 simplistic way define predicate seem after:

 subset_set([], _). subset_set([x|xs], s) :-     append(_, [x|s1], s),     subset_set(xs, s1). 

this assumes these "ordsets", is, sorted lists without duplicates.

you notice subset happens subsequence. have written instead:

 subset_set(sub, set) :-     % precondition( ground(set) ),     % precondition( is_list(set) ),     % precondition( sort(set, set) ),     subseq_list(sub, set).  subseq_list([], []). subseq_list([h|t], l) :-     append(_, [h|l1], l),     subseq_list(t, l1). 

with either definition, get:

 ?- length(sub, 3), subset_set(sub, [1,2,3,4]). sub = [1, 2, 3] ; sub = [1, 2, 4] ; sub = [1, 3, 4] ; sub = [2, 3, 4] ; false. 

you can switch order of 2 subgoals in example query, better way write it.

however, second argument must be ground; if not:

 ?- subset_set([a,b], [a,b]), b = a. = b, b = ; not real set, it? false. 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -