仅运行单个谓词时,程序将正确处理用户输入。
【代码】
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
但是,当我尝试将selectusertype谓词中给出的输入传递给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文档写得很好,因此我陷入了困境。我该如何解决?
答案 0 :(得分:1)
您可以像这样修改main
和chooseusertype
,这样的read/1
返回选择的选项:
main:-
chooseusertype(Usertype),
startas(Usertype).
chooseusertype(X):-
write('Log in as a merchant or customer?: '),
read(X),
format('Your log in type: ~w', [X]).
统一
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.