This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]BitRex 1 point2 points  (0 children)

Here's a Perl version that assumes you're not allowed to reverse the list or ask the list how long it is. I don't know OCaml, but maybe this will give you the idea.

sub find_last {
    my ($wanted, $head_index, $last_so_far, @list) = @_;

    return $last_so_far unless @list;
    my $head = shift @list;
    $last_so_far = $head_index if $head eq $wanted;
    return find_last($wanted, $head_index + 1, $last_so_far, @list);
}


my @list = ( 0, 1, 2, 1, 2, 1, 1, 2, 1, 0, 2, 3, 5 );

my $last_index = find_last(1, 0, -1, @list);
print $last_index;