Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to find the Nth element of a list, and print said element out?
    primarykey
    data
    text
    <p>so i have a homework question that asks me to find the third element of a list, as well as the last element of a list and print them out (2 separate programs).</p> <p>I Thought my Code would work to find the third element, by keeping track of a index, but i recieve a error when i try to run the code:</p> <pre><code>findthird([], Result). findthird(List, Result) :- secondFunc(List, 0, Result). secondFunc([Head|Tail], Count, Result) :- Count &lt; 3, Count is Count+1, secondFunc(Tail, Count, Result). secondFunc([Head|Tail], Count, [Head|Result]). </code></pre> <p>Have any ideas for this?</p> <p>The output i receieve now Is :</p> <pre><code>| ?- findthird([2,3,4], Result). Result = [2|_] yes </code></pre> <p>I am still having a tough time wrapping my head around Prolog, i just cant seem to understand it.</p> <p>Any help is appreciated as always,</p> <p>Thank.</p> <p>Updated with new attempt code***</p> <p>Updated ** This is the code that solved my problem:</p> <pre><code>findthird([], Result). findthird(List, Result) :- secondFunc(List, 0, Result). secondFunc([], Count, []). secondFunc([Head|Tail], Count, Result) :- Count1 is Count+1, Count1 &lt; 3, secondFunc(Tail, Count1, Result). secondFunc([Head|Tail], Count, Head). </code></pre> <p>Input:</p> <pre><code>| ?- findthird([3,4,5], Result). </code></pre> <p>Output:</p> <pre><code>Result = 5 ? yes </code></pre> <p>Input:</p> <pre><code>| ?- findthird([3,4,5,6,7], Result). </code></pre> <p>Output:</p> <pre><code>Result = 5 ? yes </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload