Fortsetzung:
Me:
Are you able to refractor your code by moving redundant parts into functions?
Chatbot:
Sure! Here is an example of how you can refactor the chatbot to move the redundant parts into functions:
Delphi-Quellcode:
program Chatbot;
{$APPTYPE CONSOLE}
uses
SysUtils, Math;
function GetNumber(prompt: string): Integer;
var
num: Integer;
begin
Write(prompt);
ReadLn(num);
Result := num;
end;
function PerformOperation(op: string): Real;
var
num1, num2: Integer;
begin
num1 := GetNumber('Enter the first number: ');
num2 := GetNumber('Enter the second number: ');
case op of
'add', 'sum':
Result := num1 + num2;
'subtract', 'difference':
Result := num1 - num2;
'multiply', 'product':
Result := num1 * num2;
'divide', 'quotient':
if num2 = 0 then
Result := NaN
else
Result := num1 / num2;
else
Result := NaN;
end;
end;
var
input: string;
result: Real;
begin
WriteLn('Hello, I am a chatbot. How can I help you today?');
while True do
begin
Write('You: ');
ReadLn(input);
if input = 'exit' then
Break;
case input of
'hi', 'hello':
WriteLn('Chatbot: Hi there! How are you doing?');
'how are you':
WriteLn('Chatbot: I am just a computer program, so I don''t have feelings. But I am here to assist you.');
'what can you do':
WriteLn('Chatbot: I can answer questions, provide information, and carry out simple tasks. Is there anything specific you would like to know or do?');
'add', 'sum':
begin
result := PerformOperation(input);
if IsNaN(result) then
WriteLn('Chatbot: Invalid input!')
else
WriteLn('Chatbot: The sum of the two numbers is ', result);
end;
'subtract', 'difference':
begin
result := PerformOperation(input);
if IsNaN(result) then
WriteLn('Chatbot: Invalid input!')
else
WriteLn('Chatbot: The difference of the two numbers is ', result);
end;
'multiply', 'product':
begin
// usw......
Me: It it looks like we could do some further refactoring
Chatbot macht dann weitere Verbesserungen..