且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog元素是列表成员检查

更新时间:2023-11-25 23:01:40

这个东西到底应该怎么称呼?看来我必须实例化N,否则N1 is N-1将不起作用.但是类似地,在您的基本情况下,N必须与1统一,因此,如果列表中存在X,则N必须等于1.因此,我认为您对此有一些基本的困惑.如果要使用N作为计数器,则可能也不能将其用作变量.不过,您应该重新考虑一下递减的思想,因为我没有任何理由期望它以适合递减的较大值被调用,除非您的代码中其他地方没有共享length/2. >

您的第二个问题是,它不会在任何地方写任何东西,并且由于您没有包括实际的问题说明,因此我不得不猜测您可能真正想做的只是返回职位,例如nth1/3.如果您只想打印出存在该元素的位置,则可以使用nth1/3来实现此目的:

write_element(X, L, N) :- nth1(N, L, X), write(N).

赔率很好,这不是故意的.如果您想实现nth1/3之类的东西,将会更加有趣,因为我们需要将要返回的计数器与使用的计数器分开.所以最终看起来像这样:

write_element(X,L,N) :- write_element_loop(X,L,1,N).

write_element_loop(X, [X|_] , N,  N).
write_element_loop(X, [_|Xs], N0, N) :-
    N1 is N0+1,
    write_element_loop(X, Xs, N1, N).

这实际上与您的代码非常接近,我只是明确了计数器和返回值之间的区别.如果要打印值而不是仅将它们统一,则可以将其添加到第一条规则的末尾:

write_element_loop(X,[X|_],N,N) :- write(N), nl.

希望这会有所帮助!

I have a little rule in prolog that has to check if an element is a member of a list and write it's position in the list,but it only works if the elemebt i'm looking for is in the 1 place.Need help please!

write_element(X,[X|_],1).
write_element(X,[_|Tail],N):-
N1 is N-1,
write_element(X,Tail,N1).

How exactly is this thing supposed to be called? It seems like N is going to have to be instantiated by me, or N1 is N-1 won't work. But similarly, N must unify with 1 in your base case, so if X is present in the list, N must equal one. So I think you have some basic confusion there surrounding how this is to be called. If you want to use N as a counter you probably can't also use it as a variable. You should revisit your thinking on decrementing though, because I don't see any reason to expect it to be called with a large value suitable for decrementing, unless there's a length/2 elsewhere in your code which you haven't shared.

Your second problem is that this does not write anything anywhere, and since you didn't include the actual problem statement I'm going to have to guess that what you probably actually want to do is just return the position, like nth1/3. We could use nth1/3 to implement this if you just want to print out the location if the element is present:

write_element(X, L, N) :- nth1(N, L, X), write(N).

Odds are good this isn't what is intended. If you want to implement something like nth1/3 it's going to be a little more interesting, because we need to keep separate the counter we're returning from the counter we're using. So it will wind up looking something like this:

write_element(X,L,N) :- write_element_loop(X,L,1,N).

write_element_loop(X, [X|_] , N,  N).
write_element_loop(X, [_|Xs], N0, N) :-
    N1 is N0+1,
    write_element_loop(X, Xs, N1, N).

This is actually really close to your code, I've just made the distinction between the counter and the return value explicit. If you want to print the values instead of just unifying them, you could add that to the end of the first rule:

write_element_loop(X,[X|_],N,N) :- write(N), nl.

Hope this helps!