问题描述
通常试图弄清楚如何将目标/函数作为参数传递。 /有点像Ruby BLOCK的概念/
在这种特定情况下,尝试使用可变数量的参数,但 call/2 只允许固定
if login_status == True:
print('User {} is already logged in.'.format(username))
if username not in users.keys():
print('username is not found')
if (username in users.keys()) and (password != users.get('value')):
print('the password is incorrect')
if (username in users.keys()) and (password == users.get('value')):
print('welcome to our new application')
第一种情况有效,即 split(Str,Lst),但调用不允许可变数量的参数。
split(Str,Lst) :- split_string(Str," ","",Lst).
split(Str,Separator,Pad,Lst).
read_line(Stream,Process,Args) :- read_line_to_string(Stream,Str),call(Process,Str,Args).
apply/2 似乎是我需要的,但被贬低了
请记住,我正在考虑除 split() 之外还有其他过程/函数
我该怎么做?
PS> 如果我有更奇怪的情况怎么办,其中第一个和最后一个参数是预先确定的,我想填充它们之间的参数。 最初我尝试过:
?- open('facts.txt',read,read_line(Str,split,P),close(Str).
Str = <stream>(0x564fc8884290),P = ["example","of.fact","\"man(socrates).\""].
如您所见,需要在两者之间填充参数。
解决方法
我不知道为什么 apply/2
被标记为已弃用(至少在 SWI-Prolog 文档中)——无论如何,您可以使用 call/2
和 =../2
轻松实现它.
另一种选择是像这样定义 read_line:
read_line(Stream,Process,Arg1) :- read_line_to_string(Stream,Str),call(Process,Str,Arg1).
read_line(Stream,Arg1,Arg2) :- read_line_to_string(Stream,Arg2).
read_line(Stream,Arg2,Arg3) :- read_line_to_string(Stream,Arg3).
% etc.,for as many args as you think are reasonable.