Prolog 元素是一个列表成员检查 [英] Prolog element is a list member check

查看:25
本文介绍了Prolog 元素是一个列表成员检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 prolog 中有一个小规则,它必须检查一个元素是否是列表的成员并将其写在列表中的位置,但它仅在我要查找的元素位于第一个位置时才有效.需要请帮忙!

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).

推荐答案

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

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.

您的第二个问题是这不会在任何地方写任何东西,并且由于您没有包含实际的问题陈述,我将不得不猜测您可能真正想要做的只是返回位置,例如 <代码>nth1/3.如果您只想在元素存在时打印出位置,我们可以使用 nth1/3 来实现:

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).

赔率很好,这不是预期的.如果你想实现类似 nth1/3 的东西,它会更有趣一些,因为我们需要将我们返回的计数器与我们正在使用的计数器分开.所以它最终会看起来像这样:

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.

希望这会有所帮助!

这篇关于Prolog 元素是一个列表成员检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆