Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › prolog anyone? [edit: got solution, still need a smidge of help]
New Posts  All Forums:Forum Nav:

# prolog anyone? [edit: got solution, still need a smidge of help]

working with prolog in school this week and wondering if anyone could lend a hand.
these are the methods i came up with so far:
Code:
``````sizeof(0, []).
sizeof(X, [_|T]) :- sizeof(Y, T), X is Y+1.

sum(0,[]).
sum(S,[H|T]) :- sum(S1,T), S is H+S1.

average(A,B) :- B\=[],sizeof(Size,B),sum(Sum,B),A is Sum/Size.

contains([X|_],X).
contains([_|T],X):- contains(T,X).```
```

The one I am working on now is finding the index of an element in a list. I was wondering if anything along the lines of using the contains method but just adding a counter at the end?
so the method is indexof(A,B,C). Where A is the index of B in C. So maybe even a different contains method that looks kinda like:
Code:
``````indexof(A,B,C):-
contains([X|_],X), ((Z =< 2, A is 1); (A is Z)).
contains([_|T],X):- contains(T,X), Z is Z+1.```
```

idk if you can catch my drift what i am trying to do.
but basically, since contains first checks if the element is the first element in the list then it does contain it.
so like if the z is less than 2 it is obviously 1'st in the list therefore it's index is 1.
otherwise, it recursively call it and then Z will increase so finally when B is the head of the list c and Z will be greater than or = to 2, A will be whatever Z is?

make sense?
Do you think im on the right track?
I just dont know exactly how to call contains using the list C!

Edited by protzman - 10/23/12 at 9:13pm
I got this to work here!
Code:
``````indexof(Index, Item, List):-
nth1(Index, List, Item).
indexof(-1, _, _).```
```

with a built in swi-prolog function, but it's based on a count starting at 1, any idea how i could reduce it to a count starting at 0?
or subtract one from the final answer?
New Posts  All Forums:Forum Nav:
Return Home
Back to Forum: Coding and Programming
• prolog anyone? [edit: got solution, still need a smidge of help]
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › prolog anyone? [edit: got solution, still need a smidge of help]