序言列表搜索 [英] Prolog List Search

查看:65
本文介绍了序言列表搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个谓词,在该谓词中,它在列表列表中搜索某个元素并返回该元素的级别.例如,当搜索元素时:

I'm trying to define a predicate where it searches a list of lists for an element and returns the level of that element. For example when searching for element:

?- elementLevel(element,[a,b,c,[d,e],[element,f]],Level).
Level = 2 .

因此,对于每个列表,它都会添加一个级别.我当时在想一个计数器,但是我不知道如何实现列表遍历.

So for every list it adds a level. I was thinking of a counter, but I don't know how to implement that for a list traversal.

推荐答案

我假设这是一项家庭作业,因此我将提供提示而不是代码.我希望这足以开发您自己的代码,因为手头的任务只是中等程度的复杂.

I am assuming that this is a homework assignment, so I would provide hints rather than the code. I hope this is sufficient to develop your own code, because the task at hand is only moderately complex.

您将需要一个事实和三个规则.

You would need one fact and three rules.

事实将忽略该元素(即使用_),将列表与空列表统一,并说返回的级别为-1(未找到).

The fact would ignore the element (i.e. use _), unify the list with an empty list, and say that the returned level is -1 (not found).

第一个和第二个规则是教科书"列表搜索,将元素与列表的开头统一,然后返回级别1;另一个规则将忽略头部,并返回元素在尾部的水平.

The first and the second rules would be the "textbook" list search, unifying the element with the head of the list, and returning the level 1; the other rule would ignore the head, and return the level of the element in the tail.

最终规则将使列表的头部与头和尾的嵌套列表统一,进行递归调用,并检查返回的值是否大于零.如果是,则返回值为嵌套的返回值加1;否则,返回值为0.否则,递归检查尾巴,并返回该检查的结果.

The final rule would unify the head of the list with a nested list of head and tail, make a recursive call, and check the returned value to see if it is more than zero. If it is, the return value is the nested return plus one; otherwise, recursively check the tail, and return the result of that check.

这篇关于序言列表搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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