如何格式化Prolog数据库实体的属性值输出(含引号与缩进)
实现Prolog数据库实体与属性的格式化输出
需求说明
使用Prolog存储实体、属性及对应值的数据库,需要按以下要求输出所有实体及其属性与值:
- 属性值必须用引号包裹;
- 通过缩进和换行提升可读性(非必需,但期望实现)。
数据库事实(不可修改)
% example objects instanceOf(ball_1, physicalObject). instanceOf(ball_2, physicalObject). instanceOf(block_1, physicalObject). % example properties propertyOf(color_ball_1, ball_1). propertyOf(size_ball_1, ball_1). propertyOf(color_ball_2, ball_2). propertyOf(size_ball_2, ball_2). propertyOf(color_block_1, block_1). propertyOf(size_block_1, block_1). % example property values hasValue(color_ball_1, red). hasValue(size_ball_1, big). hasValue(color_ball_2, blue). hasValue(size_ball_2, small). hasValue(color_block_1, red). hasValue(size_block_1, small).
已实现的谓词
% find all properties and values for one object findEveryPropertyWithValue(Object, Properties) :- instanceOf(Object, physicalObject), findall((Property, Value), (propertyOf(Property, Object), hasValue(Property, Value)), Properties). % find all objects with properties and values findAllObjects(Objects_and_Properties) :- findall((Obj, Properties), (instanceOf(Obj, physicalObject), findEveryPropertyWithValue(Obj, Properties)), Objects_and_Properties).
当前问题
- 调用
findEveryPropertyWithValue虽能得到可读结果,但属性值无引号,且需逐个触发查询; - 调用
findAllObjects可一次性获取所有结果,但输出可读性差,属性值仍无引号; - 尝试用
format/2编写格式化谓词时,无法正确遍历列表输出。
期望输出格式
Objs = [ (ball_1, [ (color_ball_1, "red"), (size_ball_1, "big") ] ), (ball_2, [ (color_ball_2, "blue"), (size_ball_2, "small") ] ), (block_1, [ (color_block_1, "red"), (size_block_1, "small") ] ) ].
解决方案
通过递归结合format/2实现格式化输出,以下是完整的谓词实现:
% 主谓词:触发查询并格式化输出所有对象 format_all_objects :- findAllObjects(Objects), format('Objs = [~n', []), format_objects(Objects), format('].~n', []). % 格式化对象列表:处理最后一个对象(无结尾逗号) format_objects([]). format_objects([(Obj, Props)]) :- format(' (~w, ~n', [Obj]), format(' [~n', []), format_properties(Props), format(' ]~n', []), format(' )~n', []). % 格式化对象列表:处理非最后一个对象(加结尾逗号) format_objects([(Obj, Props)|Rest]) :- format(' (~w, ~n', [Obj]), format(' [~n', []), format_properties(Props), format(' ]~n', []), format(' ), ~n', []), format_objects(Rest). % 格式化属性列表:处理最后一个属性(无结尾逗号) format_properties([]). format_properties([(Prop, Val)]) :- format(' (~w, "~w")~n', [Prop, Val]). % 格式化属性列表:处理非最后一个属性(加结尾逗号) format_properties([(Prop, Val)|Rest]) :- format(' (~w, "~w"), ~n', [Prop, Val]), format_properties(Rest).
使用方法
在Prolog环境中直接调用:
format_all_objects.
实现说明
- 借助你已实现的
findAllObjects获取完整数据集合; - 通过递归分别遍历对象列表和属性列表,用
format/2控制缩进、引号和换行; - 区分列表的最后一个元素,避免输出多余的结尾逗号,保证格式正确性。
内容的提问来源于stack exchange,提问作者Liz C.
相关产品推荐
相关产品推荐

