Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我尝试在递归中编写序言列表的前两个元素..例如:
如果我有
List:[a,b,c,d,e,f]
当我进入
first_two(F,S,List). It returns F:a, S:b ; F:b, S:c ; F:c, S:d ; F:d, S:e ; F:e, S:f .
我尝试这样做:
first_two(F,S,[F|[S|Tail]]):-first_two(F,S,Tail).
但它失败了..
非常感谢..
如果您想要的只是前两个,那么您的解决方案非常接近,但不需要递归:
first_two( F, S, [F|[S|_]] ).
您忘记了递归的基本情况,即终止条件:
first_two(F, S, [F, S|_Tail]). first_two(F, S, [_|Tail]) :- first_two(F, S, Tail).
我还使用友好的语法和间距简化了您的规则。
我更喜欢阅读更简单的代码,不是吗?