在Prolog中仅展平列表的一个级别 [英] Flattening only one level of a list in Prolog

查看:55
本文介绍了在Prolog中仅展平列表的一个级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个问题,以仅在Prolog中将列表的一个层次弄平.例如,[[1],[2,3]]将变为[1,2,3],但是[[1,[2]],3]仅将变平为[1,[2],3].我在网站上遇到了其他一些问题,但是没有一个人彻底回答这个问题,而且我无法让我的代码在所有测试用例上都能正常工作.

I'm working on a problem to flatten only one level of a list in Prolog. For example, [[1],[2,3]] would become [1,2,3], but [[1,[2]],3] would only flatten down to [1,[2],3]. I went through some other questions on the site, but none thoroughly answered this question, and I just can't get my code to work on all my test cases.

更新:代码有效!这是我最后来到的 answer :

Update: the code works! Here is the eventual answer that I came to:

my_flatten([], []).
my_flatten([A|B],L) :- is_list(A), my_flatten(B,B1), !, append(A,B1,L).
my_flatten([A|B],[A|B1]) :- my_flatten(B,B1).

推荐答案

您需要3个简单的子句,我只会显示最复杂的子句

You need 3 simple clauses, I will show just the most complex one

flat([H|T],R) :- is_list(H), flat(T,T1), append(H,T1,R).

另外两个子句是基本递归情况,结果为head的copy as is.

other two clauses are the base recursion case, and a copy as is of head to result.

您还应该在我显示的子句中插入一个剪切,否则回溯时会得到错误的结果(由于触发了子句copy as is)

You should also place a cut in the clause I've shown, otherwise on backtracking you'll get wrong results (due to firing of the clause copy as is)

这篇关于在Prolog中仅展平列表的一个级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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