Aaron Troeger
Aaron Troeger

Reputation: 165

Prolog sorting lists by position

I'm very new to Prolog and I'm trying to go through a list and check that each element is in the right spot of the list. for example, say you have a list of colours and each color is assigned a numerical value of 0 or 1. I want to check that all even positions in the list have the value of 0 and odd positions have a value of 1 (begin list at 0 being even).

red = 0
blue = 1
yellow = 0
orange = 1
green = 1
list1 = [red, blue, yellow, orange]
list2 = [red, yellow, orange, blue]

so basically in the example above, I'd like list 1 to come back true as its values go [0,1,0,1] and list2 to come back false as its values are [0,0,1,1]

Upvotes: 1

Views: 125

Answers (2)

rpax
rpax

Reputation: 4496

The simplest way it comes to my mind is the following:

color(red,0).
color(blue,1).
color(yellow,0).
color(orange,1).
color(green,1).

%base cases.    
colors([X]):-color(X,_).
colors([]).

colors([X,Y|Xs]):-
    color(X,Cx), %X is a color with Cx ( 0 or 1)
    color(Y,Cy), %Y is a color with Cy ( 0 or 1)
    \+member(X,[Y|Xs]), % X is not  in the list
    Cx=\=Cy, % they are different
    colors([Y|Xs]). % continue recursion.

Upvotes: 0

CapelliC
CapelliC

Reputation: 60004

For any programming language, you must follow its syntax rules. Your code seems Javascript, not Prolog. Could be instead

color(red, 0).
color(blue, 1).
...
colors(list1, [red, blue, yellow, orange]).
...

Once completed, we can write

check_colors(List) :-
  colors(List, Cs),
  forall(nth0(I, Cs, C), (N is I mod 2, color(C, N))).

You most likely need to replace forall/2 with your own 'list visit'. Start with I = 0

check_colors(List) :-
  colors(List, Cs),
  check_colors(Cs, 0).

and increment it before the recursive call. The recursion will complete (implicitly resulting in true) on empty list

check_colors([], _).

Please try to write the rest of the procedure...

Upvotes: 1

Related Questions