Explanation of a Prolog algorithm to append two lists together

前端 未结 2 938
猫巷女王i
猫巷女王i 2020-11-29 13:49

This is an algorithm to append together two lists:

Domains
list= integer*

Predicates
nondeterm append(list, list, list)

Clauses
append([], List, List) :- !         


        
2条回答
  •  孤城傲影
    2020-11-29 14:07

    Let's translate from Prolog into English. We have two rules:

    1. The result of appending any List to [] is that List.

    2. The result of appending any List to a list whose first element is H and remainder is L1 is equal to a list whose first element is also H whose remainder is the result of appending List to L1.

    So, we want to append [-10,-5,6,7,8] to [9,2,3,4]. The list being appended to isn't empty, so we can skip that rule. By the second rule, the result has 9 as the first element, followed by the result of appending [-10,-5,6,7,8] to [2,3,4].

    So, we want to append [-10,-5,6,7,8] to [2,3,4]. The list being appended to isn't empty, so we can skip that rule. By the second rule, the result has 2 as the first element, followed by the result of appending [-10,-5,6,7,8] to [3,4].

    So, we want to append [-10,-5,6,7,8] to [3,4]. The list being appended to isn't empty, so we can skip that rule. By the second rule, the result has 3 as the first element, followed by the result of appending [-10,-5,6,7,8] to [4].

    So, we want to append [-10,-5,6,7,8] to [4]. The list being appended to isn't empty, so we can skip that rule. By the second rule, the result has 9 as the first element, followed by the result of appending [-10,-5,6,7,8] to [].

    So, we want to append [-10,-5,6,7,8] to []. The list being appended to is empty, so by the first rule, the result is [-10,-5,6,7,8].

    Since the result of appending [-10,-5,6,7,8] to [] is [-10,-5,6,7,8], the result of appending [-10,-5,6,7,8] to [4] is [4,-10,-5,6,7,8].

    Since the result of appending [-10,-5,6,7,8] to [4] is [4,-10,-5,6,7,8], the result of appending [-10,-5,6,7,8] to [3,4] is [3,4,-10,-5,6,7,8].

    Since the result of appending [-10,-5,6,7,8] to [3,4] is [3,4,-10,-5,6,7,8], the result of appending [-10,-5,6,7,8] to [2,3,4] is [2,3,4,-10,-5,6,7,8].

    Since the result of appending [-10,-5,6,7,8] to [2,3,4] is [2,3,4,-10,-5,6,7,8], the result of appending [-10,-5,6,7,8] to [9,2,3,4] is [9,2,3,4,-10,-5,6,7,8].

提交回复
热议问题