Search code examples
prolog

How do I get the index of a number in a list in Prolog?


Just heads I'm fairly new to prolog so this might be a bit of a dumb question, but, Basically what I'm trying to accomplish is to get the index from a natural number, except 0, e.g.

list = [3,0,0,0,0,6]

3 has an index of 1 and 6 an index of 6

Thanks :D


Solution

  • You can use the built-in predicate nth1/3, as follows:

    ?- nth1(1, [one, two, three], Element).
    Element = one.
    
    ?- nth1(Index, [one, two, three], two).
    Index = 2 ;
    false.
    
    ?- nth1(Index, [one, two, three, one], one).
    Index = 1 ;
    Index = 4.
    
    ?- nth1(Index, [one, two, three], Element).
    Index = 1,
    Element = one ;
    Index = 2,
    Element = two ;
    Index = 3,
    Element = three.
    

    To index from 0 (instead of 1), use nth0/3.