创建PROLOG规则,根据用户输入执行以下操作:
获取要使用的整数数:
预期产出如下:
H 119输入号码:234H 220<>H 121>输入编号:67<代码>H 222<代码>H 123输入号码:8<代码>H 224<代码>H 125结果:67H 226G 227
发布于 2021-05-21 14:06:26
你不应该这样做。RPN也更易于实现和使用。
下面是一个示例计算器:
:- use_module(library(dcg/basics)).
rpn :-
prompt(_, '(number or command followed by Enter; ? for help) '),
repl([]).
repl(Stack) :-
get_token(T),
repl(T, Stack).
get_token(T) :-
read_line_to_codes(user_input, Input),
( Input == end_of_file
-> T = quit
; ( phrase(( whites, token(T), whites ), Input)
-> true
; T = error(Input)
)
).
token(number(N)) --> number(N).
token(print_stack) --> "p".
token(highest) --> "H".
token(second_highest) --> "h".
token(lowest) --> "L".
token(second_lowest) --> "l".
token(clear) --> "c".
token(help) --> "?".
token(quit) --> "q" | "quit" | "exit".
repl(quit, _) :-
format("Goodbye!~n").
repl(error(E), Stack) :-
format("Bad input: `~s'~n", [E]),
repl(Stack).
repl(help, Stack) :-
format("Add a number to the list or type:~n"),
format(" 'H' to show highest number~n"),
format(" 'h' to show second-highest number~n"),
format(" 'L' to show lowest number~n"),
format(" 'l' to show second-lowest number~n"),
format(" 'p' to print the stack, top to bottom~n"),
format(" 'c' to clear the stack~n"),
format(" '?' to show this help~n"),
format("then press Enter~n"),
repl(Stack).
repl(print_stack, Stack) :-
reverse(Stack, S),
forall(member(X, S), format("~w~n", [X])),
repl(Stack).
repl(highest, Stack) :-
max_list(Stack, X),
format("Highest: ~w~n", [X]),
repl(Stack).
repl(second_highest, Stack) :-
sort(0, @>=, Stack, [_,X|_]), % this keeps duplicates!
format("Second highest: ~w~n", [X]),
repl(Stack).
repl(lowest, Stack) :-
min_list(Stack, X),
format("Lowest: ~w~n", [X]),
repl(Stack).
repl(second_lowest, Stack) :-
sort(0, @>=, Stack, [_,X|_]),
format("Second lowest: ~w~n", [X]),
repl(Stack).
repl(clear, _) :-
repl([]).
repl(number(N), Stack) :-
repl([N|Stack]).事情是这样的:
?- rpn.
(number or command followed by Enter; ? for help) 46
(number or command followed by Enter; ? for help) 1
(number or command followed by Enter; ? for help) 234
(number or command followed by Enter; ? for help) 67
(number or command followed by Enter; ? for help) 8
(number or command followed by Enter; ? for help) ?
Add a number to the list or type:
'H' to show highest number
'h' to show second-highest number
'L' to show lowest number
'l' to show second-lowest number
'p' to print the stack, top to bottom
'c' to clear the stack
'?' to show this help
then press Enter
(number or command followed by Enter; ? for help) h
Second highest: 67
(number or command followed by Enter; ? for help) H
Highest: 234
(number or command followed by Enter; ? for help) p
46
1
234
67
8
(number or command followed by Enter; ? for help) c
(number or command followed by Enter; ? for help) p
(number or command followed by Enter; ? for help) quit
Goodbye!
true.这是一个更好的界面。
https://stackoverflow.com/questions/67613647
复制相似问题