当只运行单个谓词时,程序会正确处理用户输入。
【代码】
main:-
chooseusertype.
chooseusertype:-
write('Log in as a merchant or customer?: '),
read(X),
format('Your log in type: ~w', [X]).
【执行结果】
Log in as a merchant or customer?: customer.
Your log in type: customer
但是,当我尝试将选择用户类型谓词中给出的输入传递给 startas 谓词时
【代码】
main(-Usertype):-
chooseusertype,
startas(Usertype).
chooseusertype:-
write('Log in as a merchant or customer?: '),
read(X),
format('Your log in type: ~w', [X]).
startas('merchant'):-
write('Logged in as merchant'), nl,
write('Any update on the shelves?').
startas('customer'):-
write('Logged in as customer'), nl,
write('Let us help you find the ingredients you want!').
【执行结果】
false
它失败了。我知道语法不正确,但我发现任何 Prolog 文档写得很好,因此我陷入困境。我应该如何解决这个问题?
您可以像这样修改main
和chooseusertype
,以便read/1
返回 selectedn 选项:
main:-
chooseusertype(Usertype),
startas(Usertype).
chooseusertype(X):-
write('Log in as a merchant or customer?: '),
read(X),
format('Your log in type: ~w', [X]).
来自 SWI 文档:
起来
read(-Term)
从当前输入流中读取下一个 Prolog 术语 并将其与Term
统一
此外,如果要打印错误消息,可以执行以下操作:
main:-
chooseusertype(Usertype),
( startas(Usertype) ->
true;
format('~nUser type not recognised: ~w', [Usertype]),
fail
).
?- main.
Log in as a merchant or customer?: asd.
Your log in type: asd
User type not recognised: asd
false.