Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple nth1 predicate in Prolog

Tags:

prolog

clpfd

With SWI Prolog, there's a predicate that finds the nth item in a list called nth1. I want to implement my own version of the predicate but SWI's is so complicated if you look at the listing(nth1) code. Is there a simpler way of doing it?

Thank you :).

like image 363
ale Avatar asked Feb 25 '23 18:02

ale


2 Answers

Consider using finite domain constraints for general (reversible) integer arithmetic:

:- use_module(library(clpfd)).

nth1(1, [E|_], E).
nth1(N, [_|Xs], E) :-
        N #> 1,
        N #= N1 + 1,
        nth1(N1, Xs, E).
like image 53
mat Avatar answered Mar 08 '23 01:03

mat


I didn't mean to be contradictory or get someone else to do my work actually; I just wanted some advice, sorry for not being clearer.

I've implemented it myself now but could you guys possibly suggest improvements or better ways of doing it? What I often find myself doing in Prolog is writing a predicate with say a counter or set of counters and getting a predicate with fewer arguments to call the clauses with extra arguments. This often ends up producing quite a bit of code. Anyway, here's my implementation I just did:

item_at( N, L, Item ) :-
    item_at( N, 0, L, Item ).   
item_at( N, Count, [H|_], Item ) :-
    CountNew is Count + 1,
    CountNew = N,
    Item = H.
item_at( N, Count, [_|T], Item ) :-
    CountNew is Count + 1,
    item_at( N, CountNew, T, Item ).

Any comments? Thanks :). Usage:

?- item_at(3,[a,b,c,d,e],Item).
Item = c ;
like image 35
ale Avatar answered Mar 08 '23 01:03

ale