2015-12-30 65 views
3

首先,我是一个总Prolog新手,对于一个愚蠢的问题我表示歉意!序言列表 - 在元素前后打印列表

我需要编写一个分解月份列表的规则,并在may之前和may之后几个月打印。

到目前为止,我写了下面:

append_lists([], L, L). 
append_lists([H|L1], [L2], [H|L3]) :- 
    append_lists(L1, L2, L3). 

这个伟大的工程,如果我手动查询以下:

| ?- append_lists(Before, [may|After], [jan, feb, july, may, dec, oct, nov]). 
    Before = [jan,feb,july], 
    After = [dec,oct,nov] ? ; 
    no 

我怎么能现在重写我的规则,以便[may|After]到位规则中的L1,它可以接受任何月份?我尝试了以下方法,但没有奏效:

append_lists([], L, L). 
append_lists([Month|Before], After, [Month|Result]) :- 
    append_lists(Before, After, Result). 

回答

4

您可以使用append/3这样做。

after_and_before(Month, ListOfMonths, Before, After):- 
    append(Before, [Month|After], ListOfMonths). 

测试用例:

?- after_and_before(may, [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec], Before, After). 
Before = [jan, feb, mar, apr], 
After = [jun, jul, aug, sep, oct, nov, dec] 
+0

谢谢gusbro!这非常有帮助:) – qwerty