Write a prolog predicate insert(Num, List, NewList) that takes a number Num along with a list of numbers List which is already sorted in increasing order, and binds NewList to the list obtained by inserting Num into List so that the resulting list is still sorted in increasing order.
Write a predicate isort(List,NewList) that takes a List of numbers in any order, and binds NewList to the list containing the same numbers sorted in increasing order. Hint: your predicate should call the insert() predicate from part .
Write a predicate split(BigList,List1,List2) which takes a list BigList and divides the items into two smaller lists List1 and List2, as evenly as possible (i.e. so that the number of items in List1 and List2 differs by no more that 1). Can it be done without measuring the length of the list?
Write a predicate merge(Sort1,Sort2,Sort) which takes two lists Sort1 and Sort2 that are already sorted in increasing order, and binds Sort to a new list which combines the elements from Sort1 and Sort2, and is sorted in increasing order.
prolog主要是需要理解递归,理解之后还是比较容易写出的。
对于第一题,插入有序列表,如果插入的数字大于列表第一位,则继续递归。因此开头依然是列表数字第一位,递归后面数字,直到符合。所以需要一个新参数,来代表后面这些数字。
%base case
insert(Num,[],[Num]).
insert(Num,[A|T],[Num,A|T]) :-
Num=<A.
insert(Num,[A|T],[A|T1]):-
Num>A,
insert(Num,T,T1).