问题描述
我正在尝试在 prolog 中编写一个过程,其中如果 L1 = [1,2,3] 并且 L2 = [4,5,6] 那么 L3 = [1,4,2,5,3,6]
I'm trying to write a procedure in prolog where if L1 = [1,2,3] and L2 = [4,5,6] then L3 = [1,4,2,5,3,6]
so shuffle([1,2,3],[4,5,6],[1,4,2,5,3,6])
到目前为止我有这个:
shuffle([X],[Y],[X,Y]).
shuffle([X|Xs],[Y|Ys],_) :- shuffle(Xs,Ys,Z), shuffle(X,Y,Z).
这是我第一次尝试编写 prolog 代码,所以我仍在尝试围绕语法、规则和一切进行思考.
This is my first attempt at writing prolog code so I'm still trying to wrap my head around the syntax, rules and everything.
我理解逻辑,我只是不知道如何实现它,所以任何帮助将不胜感激!
I understand the logic, I'm just not sure how to implement it so any help would be greatly appreciated!
谢谢!
我想通了.如果有人感兴趣,这是解决方案:
I've figured it out. Here's the solution if anyone's interested:
shuffle([X],[Y],[X,Y]).
shuffle([X|Xs],[Y|Ys],[Z1,Z2|Zs]) :- shuffle([X],[Y],[Z1,Z2]),shuffle(Xs,Ys,Zs).
推荐答案
shuffle([], B, B).
shuffle([H|A], B, [H|S]) :- shuffle(B, A, S).
在这类问题中,通常困难的部分不是Prolog,而是找出解决它的最简单的递归关系.
In this kind of problems, usually the difficult part is not Prolog but identifying the simplest recursive relation that solves it.
这篇关于在序言中随机播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!