在Prolog中将返回值从一个谓词传递给另一个谓词

在Prolog中将返回值从一个谓词传递给另一个谓词,prolog,Prolog,当只运行一个谓词时,程序会正确地处理用户输入 【代码】 main:- chooseusertype. chooseusertype:- write('Log in as a merchant or customer?: '), read(X), format('Your log in type: ~w', [X]). main(-Usertype):- chooseusertype, startas(Usertype). chooseuser

当只运行一个谓词时,程序会正确地处理用户输入

【代码】

main:-
    chooseusertype.

chooseusertype:-
    write('Log in as a merchant or customer?: '),
    read(X),
    format('Your log in type: ~w', [X]).
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!').
【执行结果】

Log in as a merchant or customer?: customer.
Your log in type: customer
false
但是,当我尝试将chooseServerType谓词中给定的输入传递给startas谓词时

【代码】

main:-
    chooseusertype.

chooseusertype:-
    write('Log in as a merchant or customer?: '),
    read(X),
    format('Your log in type: ~w', [X]).
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!').
【执行结果】

Log in as a merchant or customer?: customer.
Your log in type: customer
false

它失败了。我知道语法不正确,但我没有发现任何编写得很好的Prolog文档,因此我陷入了困境。我该如何解决这个问题

您可以像这样修改
main
chooseServerType
,例如taht
read/1
返回choosen选项:

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术语 并将其与
术语

此外,如果要打印错误消息,可以执行以下操作:

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.

非常感谢你!这正是我一直在寻找的答案:)