博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lists in Prolog
阅读量:6434 次
发布时间:2019-06-23

本文共 2083 字,大约阅读时间需要 6 分钟。

Symbols  in Prolog:
atom
variable
number
list  (how to  assembly  and  take them apart )
 
Lists are very  powerful  in prolog because we do not need to do similar but 
repeated tasks again and again. Instead, we can put all elements in a list and deal with them in a more 
general way.
 
If we have a look at the 
difference  between 
lists  in prolog and 
arrays  in C, it is easy to notice that we 
do not need to define the length of a list in prolog . Instead, we use a recursive  way to deal with them one by one until the remaining is empty.
 
How to 
write
 a list:
use 
commas  to separate every element:  [A, B]
use 
vertical bars  to divide head and tail:   [A | B]
 
The two definitions are quite 
different
When using 
[A, B] , the list has 
only 2  element A and B.
When using  
[A | B] , the list can have 
at least 1  elements because B is a list and it can be empty or very large.
 
How to 
operate
 on a list:
Define a 
stop condition  for the recursion;
Deal with lists 
recursively  (always divide the list by head and tail) 
decreasing the length  of it.
 
Examples:
 
example 1: members in a list
 
elem(A, [A | _]).
elem(A, [_ | B]) :- elem(A, B).
 
If we use the following instead, it will only hold when A is the tail of the list.
elem(A, [A]).
elem(A, [_ | B]) :- elem(A, B).
 
 
example 2: list of unique people
 
uniq([ ]).
uniq([H | T]) :- people(H), \+ member(H, T), uniq(T).
 
example 3: joining two lists
 
join([ ], T, T).
join([H | T], L, [H | W]) :- join(T, L, W).
 
We can learn from these examples that we use [H | T] to take the lists into head and tail decreasing the length of it to solve our problem.
 
Using 
append
 predicate
append predicate is powerful is because it can 
analyze the structure of a list .
Notice that the  parameter  of append predicate 
must be lists or variables  not atoms.
 
append([a, b], [c, d], L).
L=[a, b, c, d].
 
Examples:
 
L1 is start of L2:
front(L1, L2) :- append(L1, _, L2).
 
E is last element of L:
last(E, L) :- append(_,  [E] , L).
 
another version of member predicate:
mem(A, B) :- append(_, [A | _], B).
 
X is before Y in L:
before(X, Y, L) :- append(Z, [Y | _], L), append(_, [X | _], Z).

转载地址:http://hcxga.baihongyu.com/

你可能感兴趣的文章
去美国考托福还是雅思?雅思更简单实用
查看>>
PostgreSQL 性能优化
查看>>
HTML基础之JS
查看>>
剑指offer:第一个只出现一次的字符
查看>>
protobuf for lua in Mac
查看>>
决策树
查看>>
Web 前端颜色值--字体--使用,整理整理
查看>>
五、MySQL 创建数据库
查看>>
redis安全配置
查看>>
作业15-导航,头部,CSS
查看>>
DecimalFormat用法
查看>>
用javascript去掉字符串空格的办法
查看>>
test
查看>>
JAVA编程题-用java解决兔子问题
查看>>
pychon笔记
查看>>
[转] Web前端研发工程师编程能力飞升之路
查看>>
简单理解桶排序
查看>>
C#项目代码规范
查看>>
vscode常用插件
查看>>
算法的时间复杂度比较,计算多项式的直接法和秦九韶法
查看>>