AlwaysThresh
AlwaysThresh

Reputation: 73

Creating a list in Prolog based on some specifications

I am working on a side project in which I am attempting to create a Prolog function that makes a list of atoms, but it must ensure some atoms come before others. Essentially a list of tasks that must be completed however some of the tasks are prerequisites for other tasks.

For example:

task(brushteeth).
task(usemouthwash).
task(gotowork).

prereq(usemouthwash, brushteeth).
%where brush teeth must be done prior to using mouthwash

I however am having a rough time even creating a list in the first place that can list all of the tasks, let alone having the prerequisites come before other tasks.

Any guidance would be awesome, I am certainly not asking anybody to write this for me I just need a general working example or something to get me started. I have searched an attempted to modify so many things I just can't get anything to work anymore.

Thank you in advance, I a apologies if this question seems vague or unhelpful. I am just really stuck.

Upvotes: 1

Views: 52

Answers (1)

coder
coder

Reputation: 12972

You could start thinking from base cases since you're more likely to write a predicate using recursion:

create_list([]). %zero element list is accepted, same for one element below:
create_list([X]):- task(X).
create_list([X,Y|Rest]):- prereq(X,Y), create_list([Y|Rest]).

And finally list of fixed length:

create_list_len(L,N):- length(L,N), create_list(L).

Example with facts:

task(brushteeth).
task(usemouthwash).
task(gotowork).

prereq(usemouthwash, brushteeth).
prereq(gotowork, usemouthwash).

create_list(L).
L = []
L = [brushteeth]
L = [usemouthwash]
L = [gotowork]
L = [usemouthwash, brushteeth]
L = [gotowork, usemouthwash]
L = [gotowork, usemouthwash, brushteeth]
false

create_list_len(L,3).
L = [gotowork, usemouthwash, brushteeth]

Upvotes: 2

Related Questions