'atoms' 的编译时间测试
Compile time testfor 'atoms'
prolog 的全新内容。到目前为止,我在尝试改变我的想法方面经历了一段有趣的旅程,非常感谢这里的任何帮助。
我正在尝试为一组预定义的名称断言事实。例如,假设我在一个文件中有一组人 [alice, bob, ...]。我想在其他文件中断言关于这些人的事实,但想确保这些人存在并且在事实 loaded/compiled(?).
时进行检查
例如,假设我在列表中没有 'chuck',并且我断言:
用户:swipl app.pl
?- full_name(chuck, "Charlie Steel").
应该会导致错误。
最好的方法是什么?
所以,这是我想出的代码:
person(deborah).
person(tony).
read_my_file(Filename) :-
open(Filename, read, In),
read_my_file1(In),
close(In).
read_my_file1(In) :-
read(In, Term),
( Term == end_of_file
-> true
; assert_or_abort(Term),
read_my_file1(In)
).
assert_or_abort(Term) :-
( full_name(Person, Name) = Term
-> ( person(Person)
-> assertz(full_name(Person, Name))
; format(user, '~w is not a person I recognize~n', [Person])
)
; format(user, '~w is not a term I know how to parse~n', [Term])
).
这里的技巧是使用 read/2
从流中获取 Prolog 项,然后对其进行一些确定性测试,因此在 assert_or_abort/1
内嵌套了条件结构。假设您有一个如下所示的输入文件:
full_name(deborah, 'Deborah Ismyname').
full_name(chuck, 'Charlie Steel').
full_name(this, has, too, many, arguments).
squant.
你得到这个输出:
?- read_my_file('foo.txt').
chuck is not a person I recognize
full_name(this,has,too,many,arguments) is not a term I know how to parse
squant is not a term I know how to parse
true.
?- full_name(X,Y).
X = deborah,
Y = 'Deborah Ismyname'.
prolog 的全新内容。到目前为止,我在尝试改变我的想法方面经历了一段有趣的旅程,非常感谢这里的任何帮助。
我正在尝试为一组预定义的名称断言事实。例如,假设我在一个文件中有一组人 [alice, bob, ...]。我想在其他文件中断言关于这些人的事实,但想确保这些人存在并且在事实 loaded/compiled(?).
时进行检查例如,假设我在列表中没有 'chuck',并且我断言:
用户:swipl app.pl
?- full_name(chuck, "Charlie Steel").
应该会导致错误。
最好的方法是什么?
所以,这是我想出的代码:
person(deborah).
person(tony).
read_my_file(Filename) :-
open(Filename, read, In),
read_my_file1(In),
close(In).
read_my_file1(In) :-
read(In, Term),
( Term == end_of_file
-> true
; assert_or_abort(Term),
read_my_file1(In)
).
assert_or_abort(Term) :-
( full_name(Person, Name) = Term
-> ( person(Person)
-> assertz(full_name(Person, Name))
; format(user, '~w is not a person I recognize~n', [Person])
)
; format(user, '~w is not a term I know how to parse~n', [Term])
).
这里的技巧是使用 read/2
从流中获取 Prolog 项,然后对其进行一些确定性测试,因此在 assert_or_abort/1
内嵌套了条件结构。假设您有一个如下所示的输入文件:
full_name(deborah, 'Deborah Ismyname').
full_name(chuck, 'Charlie Steel').
full_name(this, has, too, many, arguments).
squant.
你得到这个输出:
?- read_my_file('foo.txt').
chuck is not a person I recognize
full_name(this,has,too,many,arguments) is not a term I know how to parse
squant is not a term I know how to parse
true.
?- full_name(X,Y).
X = deborah,
Y = 'Deborah Ismyname'.