Taking advantage of AI to help you write code

Introduction to AI in Software Development

Discussion about the explosive popularity of AI and its increasing role in software design and development. Emphasis on the transformation of ideas into computer instructions and the turbocharging capabilities of AI in enhancing creativity and problem-solving.

Exploring AI Tools in Software Industry

Exploration of various AI tools transforming the software industry, including conversational AI chatbots (ChatGPT, Bing Chat, Google Bard) and IDE extensions (GitHub Copilot, Amazon CodeWhisperer, Tab9, AskCodey). Focus on their integration with IDEs and capability to interpret code context and comments.

FizzBonacci Sequence Challenge

Presentation of a unique challenge combining the Fibonacci sequence with FizzBuzz rules to test AI tools. Demonstration of the tools' outputs and limitations in coding the 'FizzBonacci' sequence in TypeScript.

Benefits of Working with AI in Software Development

Discussion of the benefits of AI tools in ideation, generating boilerplate code, implementing functions based on specifications, and aiding in code review and debugging. Emphasis on AI's role in offering diverse perspectives and innovative solutions.

Limitations and Risks of AI Tools

Analysis of the limitations and risks associated with AI tools, including potential inaccuracies, lack of project context, and issues like leaking confidential secrets and copyright concerns. Mention of companies' approaches to handling these risks.

Prompt Engineering and AI Responsiveness

Examination of different prompting techniques such as zero-shot, few-shot, and chain of thought prompting. Demonstration of how these techniques influence AI's response accuracy and effectiveness.

Building an App with ChatGPT

Walkthrough of building a calculator app using ChatGPT, covering aspects from concept generation to implementation. Insights into the learning process and interaction with ChatGPT for debugging and enhancing the app.

Conclusion and Reflection on AI Tools

Conclusion highlighting the educational benefits and potential of incorporating AI in software development. Open floor for questions and further discussion.

AI has absolutely exploded in popularity over the last year.

It's likely to play an increasingly important role in the way we design and develop software in the future.

Fundamentally, software development is about taking our ideas and transforming them into instructions that a computer can follow.

Whether we do this by writing machine code or a higher level programming language, or by engineering prompts to get the computer to generate that for us.

So AI is here to turbocharge capabilities.

it's here to help us work smarter and faster and enhance our creativity to solve complex problems.

As developers, we need to learn to embrace AI, to understand it, and to harness it to its full potential.

Let's start, by exploring the landscape of AI tools that are transforming the software industry.

First up, we have the conversational AI chatbots, including ChatGPT, Bing Chat, and Google Bard.

These ones can generate snippets of code based on your prompts.

And you can iteratively refine your solutions.

then we have the IDE extensions, GitHub Copilot.

Amazon CodeWhisperer, Tab9, and AskCodey.

These ones integrate seamlessly with your IDE, and they can utilize context from your code base.

They can read your comments, turning them into effective prompts.

Basically, those are like pair programming with someone who actually knows how to code.

we're going to see how each of these tools performs in a real world application.

We're going to ask them to generate some code based on a given prompt.

when it comes to choosing a, Problem that we can do for this demonstration.

I thought about Fibonacci sequence or the FizzBuzz one.

These are quite common, but I just wanted something simple.

However, since they are so common, we're also likely to get pre canned answers from AI.

So I wanted to step it up a notch with something a little bit more interesting and challenging.

So I came up with the FizzBonacci sequence, the Fibonacci sequence numbers with the FizzBuzz rules applied to it.

Here's the prompt.

Create a generator function called fizzbonacci in TypeScript that accepts two parameters as the first two numbers in the Fibonacci sequence.

The output should follow the rules of fizzbuzz.

Then create an array of length 20 populated with the values from this generator.

So first up, we have chat gpt.

at first glance, it looks pretty reasonable.

It's generating the Fibonacci sequence correctly.

It's applying the rules for FizzBuzz.

and then it's populating an array with 20 values.

However, when we look at the output, it forgot to yield the first two values.

Then I moved on to, Bing Chat.

This one is fundamentally based on ChatGPT4 under the hood.

So we expect somewhat similar results.

and we can see it's also, iterating.

This one is actually yielding the first two values.

But when it went to creating the array, it made a mistake and just output fizzbuzz for everything.

So I fixed that bug and then it actually did, output the correct result for me.

Not too bad overall.

Finally, the last of the chat, bots, we have Google Bard.

This is Google's attempt and, it looks somewhat similar to the chatGPT4 result.

and when we look at the result, it also forgot to yield the first two values.

But otherwise, not too bad.

Then we move on to the IDE extensions, starting with GitHub Copilot.

So this one integrates directly with your IDE, unfortunately, I had to modify the prompt a bit, just to explain the rules of fizzbuzz.

For some reason it didn't know.

but then we found that the function it generated is just giving me the Fibonacci sequence.

And then it's applying the rules for fizzbuzz as it populates the array separately.

It's not quite what I asked for, but it more or less gave me a result but it also did forget to yield the first two values.

Seems like a common problem.

I guess it's been trained on, university students, who also make the same mistake.

Amazon CodeWhisperer just completely forgot about the rules of FizzBuzz and just gave me Fibonacci.

yeah.

but at least to its credit, it did remember to yield the first two values.

Tab9 on the other hand did the opposite.

It just gave me FizzBuzz.

And then finally, AskCody.

This one actually managed to get things mostly correct.

the only mistake it made is it forgot to pass the seed values to the fizzbonatti function.

so when I fixed that value, it actually gave me correct output.

except it did the numbers of strings, but whatever.

yeah, so there are numerous benefits to working with AI.

starting with the conversational AI tools.

These ones are great for ideation.

You can explore ideas, they can provide different perspectives and offer suggestions that you might not have otherwise thought of.

so not only does it save time, but can also help you, lead to innovative solutions that you might not have considered.

They're good at generating boilerplate code, or at least large chunks of code that is monotonous and time consuming to type out.

So you may as well get AI to generate that for you, so you can focus more on the interesting and unique parts of your application.

They're very good at implementing, functions based on specifications or describe, or descriptions.

so if you give it a clearly described, description of what you want.

it will give that to you and it can, lead to, fewer errors and stuff like that.

Finally, code review and debugging.

you can actually give these chat bots, snippets of your code.

It can analyze them and it can understand what they do, and it can also point out to, potential bugs, opportunities for optimization, and perhaps provide, suggestions for things you might not have considered.

On the other hand, AI extensions for IDEs have their own unique, benefits.

So these tools can supercharge your coding efficiency with predictive text capabilities.

They can offer intelligent, suggestions, sometimes.

so they're also good at generating test suites.

By analyzing your code and taking prompts that, describe the expected behavior, they can very quickly generate a whole bunch of, test cases for you, helping you to make sure your code works as you want it to.

They have contextual awareness since they have, access to your entire code base.

The suggestions can be more relevant.

It can, follow the same sort of coding patterns that you use throughout your repo.

But they do, all of these tools come with some limitations and risks.

So we'll cover those.

As we've seen in my previous demo, there's no guarantee that the, code they generate will be accurate.

It may not compile, it may not run, or if it does, it may not be bug free.

So just like we're copying code from Stack Overflow, we also, we need to make sure that the code we're given does what we expect.

It's our responsibility as developers to do that.

So as powerful as these tools are, it's important to remember that they lack the wider context of your project.

Your AI tool hasn't been sitting in your last meeting discussing the project requirements.

It doesn't know all that.

It doesn't understand your unique user requirements So you can help it by providing some additional context, or by letting it scan your repo.

But it's not a replacement for a deep understanding of your unique project's requirements and constraints.

Though it's a tool that can provide suggestions, but it's your knowledge and expertise that shapes those suggestions into the final product.

Leaking confidential secrets, not a big issue.

Companies like Apple, Amazon, and Google have publicly announced policies limiting their employees access to these tools for work purposes.

They don't want their secrets, leaked to, third party services.

Samsung employees publicly did this, there were articles about it.

other companies are addressing these issues either by self hosting their own AI tools or by establishing contracts with these AI services that outline specific requirements for how their employee data is handled.

Copyright is another big issue.

GitHub Copilot is currently under a class action lawsuit alleging that they violated copyright.

Because they, the training data was based on publicly available GitHub repos.

As a result, it can generate code that closely resembles copyrighted code, regardless of the original code's license.

While this question, and others like it, are ultimately up to the legal experts to decide, which is not me, it's important to understand that this is a potential risk, as we learn to use AI.

Moving on to prompt engineering.

This is the practice of formulating your prompts to get the result that you want.

So the first is zero shot prompting.

This is the basic prompt where you give the AI a simple question or say, just generate this for me and we'll do it.

You're not giving it any.

Additional information or examples.

So for example, write a TypeScript function that has adds, takes two numbers and adds them together.

It's a fairly simple request and we would reasonably expect it to do this for us.

Next up, we have few shot prompting.

This is where we give the AI some examples of how we would like it to respond, and then ask the question, and then it responds based on our example.

So for example, here I've written a test case for the previous function, and then I said, write some more tests.

So here it has generated tests for handling zero, negative numbers, floating point numbers, large numbers.

And with some little extra encouragement, you can handle edge cases like not a number or infinity.

While this is a trivial example, it's easy to apply the same concept to more complex functions that you're actually working on.

Chain of thought prompting builds on these, where you, and you use the power of conversation to guide the AI, through a reasoning process, which can lead to more accurate responses.

So zero shot COT, similar to the zero shot prompting, where we just tell the AI to think step by step, and few shot COT, where we actually provide exemplars demonstrating how we would, like the AI to respond to similar problems before providing our, actual question we want.

So here's an example of zero shot COT.

So write a TypeScript function to calculate the average length of the array, whatever it is, the average of the integers, and let's think step by step.

This is enough to force the AI into actually thinking about step by step.

So first it declares the function, adds the numbers, then it divides by the length, and then finally it considers edge cases.

So this.

The kind of approach is likely to lead to a better response than if you just asked it to give me the final answer at the end.

let's move on to actually building an app with ChatGPT, where we understand the fundamentals.

So I thought, what better way to find out what to build?

Ask ChatGPT.

With suggestions like the to do list, the weather app, stopwatch, currency converter, all that.

I was like, I wanted something that I could learn from.

I thought, I don't know how a calculator works internally.

I wonder what ChatGPT could teach me about that.

So that's what I chose to work on.

So I asked, how does a calculator work from a high level?

And I need to handle user input, parsing, evaluation, and display of the result.

So I said, all right, I'm building this.

What's the first component?

And it's just given me a calculator component.

I told it I'm doing React and TypeScript.

And I set up a basic, stuff framework for that.

yeah.

And so it's done that.

And it's left placeholders for the buttons and the display.

Next I said, okay, ready for the next step.

And it created me a number button component.

Just a simple button with an on click handler.

All right.

And I told it, okay, thanks.

Integrate that into the thing.

So it's added, created an on click handler that handles when the button is pressed.

And it's added all nine or 10 buttons, starting from seven, eight, nine at the top.

So it understood the calculator button layout.

For those unaware, calculator buttons go from bottom to top, phone buttons go top to bottom.

So when I told it, I created an operator button component based on the number button component.

I said, just give me the basic operations.

It added the multiply, divide, add, subtract, and it, it added a handle operator click function as well.

oh yeah, I noticed a bug.

The simple implementation, when you click any button, you bring out this value, it just concatenates the result.

So when it's zero, on a normal calculator, you want it to replace the value.

so I just told it what the bug was, and it handled that for me.

I told it I needed an equals button, and it, gave me a, an equals button and it updated the display for me when the equals button is clicked.

It's pretty good.

So then I thought, at the moment it's just completely unstyled HTML button.

It looks pretty terrible.

I was like, all right, give me a style sheet.

And it did.

And with some minor modifications, here's basically what it looked like.

It's not the best design.

Your designer's job is safe for now.

but it's functional.

Good enough for the demo.

And I added a couple more buttons along the way as well.

But this is using eval internally.

It's just calling the JavaScript eval function whenever equals is pressed.

I was like, I actually want to learn more.

I don't want to rely on pre written code for this.

So let's find out, how does a calculator work internally?

What are the internal algorithms?

back to ChatGPT.

It told me about the shunting yard algorithm and reverse polish notation.

So the shunting yard algorithm, reverse polish notation is a way of expressing writing expressions, that, where the operator is placed after the numbers it works on.

You're probably familiar with the infix notations we learned in school.

It's what we all write in JavaScript these days.

We have multiply, so two times three plus four times five.

And then this is evaluated by doing the multiplication first and then adding those two together.

In this case, we get 26.

In reverse polish notation, we instead flip that around.

So we have the two numbers, then an operator, then another two numbers, then the operator, and then the final operator for the final results.

So you evaluate left to and then just apply the operators in the order they show up.

So no need for brackets in this notation.

So again, we do two times three, four times five, add them together, get So that's the fundamentals.

The shunting yard algorithm is how we convert from the infix notation, so what a normal person would write, into reverse polish notation.

So this is how it works.

Imagine that the lines here represent train tracks and the numbers and operators represent trains being shunted around in the train yard.

When you get a number, it just goes straight into the output queue.

When an operator is encountered, it gets pushed into the operator stack initially.

When an operator of lower precedence is encountered.

the operator is first popped off the operator stack.

Then the new one is placed in.

When an operator of higher precedence is encountered, it's just pushed onto the operator stack.

and then when there's no more input, the operator stack is cleared.

So we've gone from infix notation to the final output.

So then I asked, ChatGPT, implement it for me.

Give me a, a function to convert from infix to RPM.

And this is what it gave me.

It looks pretty reasonable.

It's handling numbers, operators, parentheses.

So yeah, took that code.

Great.

I also need to evaluate the RPM.

So it gave me an evaluateRPM function where it iterates over the input, yeah, adds numbers and stuff into the, queue.

It has the operator stack.

Great.

Took that code.

Let's see how it performed.

So this was the conversion to RPM, result.

Doesn't quite look the same as what I showed earlier, but let's see.

So we do 4 and 5, multiply.

Then we add, 3 and 20.

And then we multiply, what is that, 2 and 23.

And get 46.

not great.

explaining this, bug, the bug was that, it wasn't checking the operator queue.

sorry, the operator stack before pushing a new operators, into there.

It needed to check what the precedence of the current operator was, and then pop it if needed.

so just explained what that bug was and it gave me a new updated function.

let's see how it works.

Oh, and also write a precedence function where, just returns a number.

So what's the precedence?

It's pretty simple.

So this time It gave me the correct IPN, which as I showed earlier, evaluates to the correct result.

Great.

We have a working calculator.

Took these functions, put them into my calculator.

All right.

So this is the calculator here.

yeah.

So as I showed before, I've got, two times three plus four.

Oh, I can see five.

Ah, whatever.

Okay.

Clear entry.

That actually does work.

there we go.

So this should give me 26.

I also, worked with ChatGPT to just improve it a bit.

so if we do eight, times, open brackets, two plus three.

I put implicit bracket closing, so I don't need to bother doing it again.

and then, I assume that's correct, 8 times 5.

Yeah, yeah, so this is the calculator.

It works.

it handles, ignoring that, if I do, minus, when I type 58, I get a 0.

Ah, 58.

that.

Yeah, it knows if it is zero, then it just replaces the value.

yeah, I can do times, whatever, zero, one, it works.

Yeah, so that's pretty much it.

so yeah, what I learned is that AI tools are great.

They can, they can, teach you stuff.

I learned a lot while doing this, and I am going to be incorporating a lot of AI, into my development going forward.

any questions?

AI is Important

Amplifying our capabilities, enhancing our creativity to solve complex problems

A serene landscape with a vibrant blue sky and a few contrails, overlooking a verdant green field peppered with a scattering of trees. Logos represent ChatGPT, Bing Chat, Google Bard, GitHub Copilot, Amazon CodeWhisperer, TabNine, AskCodi.

Generating Code

A scenic view of a coastline with a row of wind turbines under a blue sky with some clouds. The mountains are visible in the background.

Fibonacci

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

FizzBuzz

1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, ...

Fizzbonacci

1, 1, 2, "Fizz", "Buzz", 8, 13, "Fizz", 34, "Buzz", 89,

Create a generator function called "fizzbonacci" in TypeScript

Create a generator function called "fizzbonacci" in TypeScript that accepts 2 parameters as the first 2 numbers in the Fibonacci sequence. The output should follow the rules for FizzBuzz.

Create an array of length 20 populated with values from this generator.

PROMPT

Here's a TypeScript implementation of the "fizzbonacci" generator function, as well as code to populate an array of length 20 with values from this generator:

function* fizzbonacci(a: number, b: number) {
  while (true) {
    let c = a + b;
    a = b;
    b = c;
    let value: string | number = c;

    if (c % 3 === 0 && c % 5 === 0) {
      value = "FizzBuzz";
    } else if (c % 3 === 0) {
      value = "Fizz";
    } else if (c % 5 === 0) {
      value = "Buzz";
    }

    yield value;
  }
}

const firstNumber: number = 1;
const secondNumber: number = 1;
const fizzbonacciGenerator = fizzbonacci(firstNumber, secondNumber);
const fizzbonacciArray: Array<string | number> = [];

for (let i = 0; i < 20; i++) {
  fizzbonacciArray.push(fizzbonacciGenerator.next().value);
}
There are no images, diagrams, tables, graphs in the image to describe.
shows the output of running the code in a terminal window.

Create a generator function called "fizzbonacci" in TypeScript that accepts 2 parameters as the first 2 numbers in Fibonacci sequence. The output should follow the rules for FizzBuzz. Create an array of length 20 populated with values from this generator.

Here’s a TypeScript implementation of the “fizzbonacci” generator function that you can use:

function* fizzbonacci(first: number, second: number) {
  let current = first;
  let next = second;
  while (true) {
    let value = current;
    if (value % 3 === 0 && value % 5 === 0) {
      yield 'FizzBuzz';
    } else if (value % 3 === 0) {
      yield 'Fizz';
    } else if (value % 5 === 0) {
      yield 'Buzz';
    } else {
      yield value;
    }
    [current, next] = [next, current + next];
  }
}

This code creates a generator function called fizzbonacci that accepts two parameters first and second as the first two numbers in the Fibonacci sequence. The function then uses a while loop

shows the output of running the code in a terminal window.

Create a generator function called "Fizzbonacci" in TypeScript

Create a generator function called "Fizzbonacci" in TypeScript that accepts 2 parameters as the first 2 numbers in Fibonacci sequence. The output should follow the rules for FizzBuzz. Create an array of length 20 populated with values from this generator.

Here's a TypeScript FizzBuzz generator function that you can use:

function* fizzbuzz(value: number): Generator<string | number> {
  let current = value;
  let next = value + 1;
  while (true) {
    let value = current;
    current = next;
    next = value + current;
    if (value % 3 === 0 && value % 5 === 0) {
      yield 'FizzBuzz';
    } else if (value % 3 === 0) {
      yield 'Fizz';
    } else if (value % 5 === 0) {
      yield 'Buzz';
    } else {
      yield value;
    }
  }
}

const fibonacciSequence = [...Array(20)].map((_ , i) => fizzbonacci(0, 1).next().value);

Create a generator function called "fizzbonacci" in TypeScript that accepts 2 parameters as the first 2 numbers in Fibonacci sequence. The output should follow the rules for FizzBuzz.

Create an array of length 20 populated with values from this generator.

Sure, here is the generator function called "fizzbonacci" in TypeScript that accepts 2 parameters as the first 2 numbers in Fibonacci sequence. The output should follow the rules for FizzBuzz.

TypeScript

function* fizzbonacci(a: number, b: number) {
  let i = 0;
  while (i < 20) {
    let c = a + b;
    a = b;
    b = c;
    if (c % 3 === 0 && c % 5 === 0) {
      yield "FizzBuzz";
    } else if (c % 3 === 0) {
      yield "Fizz";
    } else if (c % 5 === 0) {
      yield "Buzz";
    } else {
      yield c;
    }
    i++;
  }
}

const array = [...fizzbonacci(0, 1)];
shows the output of running the code in a terminal window.
shows function created by github copilot
shows the output of running the code in a terminal window.
shows function created by CodeWhisperer
The image shows a text editor window with TypeScript code for a function named 'fizzbonacci'. Next to the editor window, there is a terminal output showing the result
shows function created by Tabnine
shows function created by Ask Codi
shows the output of running the code in a terminal window.

Ideation

Good for exploring new ideas

A man in profile view writing on a sticky note in front of a whiteboard. The whiteboard is covered with multiple colorful sticky notes.

Generating Boilerplate

Good for generating a lot of boilerplate code in big chunks

An image of a metallic surface, possibly part of a train or machinery, with a plate that reads "CANADIAN PACIFIC RAILWAY".

Rapid Function Implementation

Able to implement well-known or clearly described functions quickly

The image features a black and white photo of a group of male athletes in the starting blocks at the beginning of a track race, capturing the moment as they start.

Code Review and Debugging

Suggest improvements to your existing code

Benefits of AI Extensions for IDEs

Supercharged Autocomplete

Intelligently predict what you're likely to need next

The Castle (1997)

GIF of a scene from the Castle where an assistant passes unhelpful notes to the Barrister as he addresses the court.

Test Suite Generation

No-one likes writing tests.

Let your friendly AI do it for you

Contextual Awareness

Leveraging your entire codebase for smarter suggestions

A person standing on a rock outcrop with arms spread wide, facing a scenic landscape of winding riverbeds, sandbanks, and a mountain range in the background.

Limitations and Risks

The image features a person sitting on the edge of a cliff with their legs dangling over the side, high above a blanket of clouds. The person appears relaxed and is gazing into the distance.

Inaccurate Code Suggestions

There’s no guarantee that code offered by AI will actually compile or run

A person looking frustrated or stressed out, with hands on their head, in front of a laptop screen.

Limited Context

Your AI tool hasn’t been attending your planning meetings, it only knows what you tell it.

Leaking Confidential Secrets

Company NDAs can prohibit employees from sharing information with AI tools

© Copyright

Who owns the copyright on AI generated code?

class='slide-text'>

Prompt Engineering

Two construction workers, one male and one female, wearing safety vests and helmets, are looking at a set of blueprints on a construction site.

Prompt Engineering

A simple prompt with no extra information, but you expect the model can generate the desired result

Zero Shot Prompting

Few Shot Prompting

Chain of Thought Prompting

Prompt Engineering

Zero Shot Prompting

BL Write a TypeScript function that takes two numbers and returns their sum.

Sure, here's how you can define such a function in TypeScript:

function addNumbers(num1: number, num2: number): number {
  return num1 + num2;
}

This function, named 'addNumbers', takes two arguments 'num1' and 'num2', both of type 'number'. It returns a value of type 'number', which is the sum of 'num1' and 'num2'.

Few Shot Prompting

Chain of Thought Prompting

Prompt Engineering

Zero Shot Prompting

Few Shot Prompting

Within your prompt, include one or more examples of how you would like it to respond to similar tasks, before asking it to solve the task you want

Chain of Thought Prompting

Prompt Engineering

Zero Shot Prompting

Few Shot Prompting

Within your prompt, include one or more examples of how you would like it to respond to similar tasks, before asking it to solve the task you want

Example:

it("should add two positive integers", () => {
    expect(addNumbers(3, 5)).toBe(8)
})

Write more tests for different types of numbers

Chain of Thought Prompting

further answers to the above example question

Prompt Engineering

Zero Shot Prompting

Few Shot Prompting

Chain of Thought Prompting

Use the power of reasoning to guide Al towards more accurate responses

Zero Shot CoT

Add "Let's think step by step" to the end of your prompt

Few Shot CoT

Provide exemplars demonstrating the reasoning process you want the Al to use

Prompt Engineering

Zero Shot Prompting

Few Shot Prompting

Chain of Thought Prompting

Write a TypeScript function to calculate the average of an array of integers. Let's think step by step.

Response to the prompt

Building an App

with ChatGPT

The image features a humanoid robot wearing a yellow safety hat, seemingly sitting or crouching with one arm resting on a knee.

Generate a list of ideas for javascript based applications that I could create for the purpose of a 10 minute presentation

Sure, here are some ideas for JavaScript based applications that you could create for a 10 minute presentation:

  • Todo List - A simple todo list application where users can add, edit and delete tasks.
  • Calculator - A simple calculator that performs basic arithmetic operations.
  • Weather App - An application that displays the current weather for a given location, using a weather API.
  • Random Quote Generator - An application that displays a random quote every time a button is clicked.
  • Stopwatch - A stopwatch application that can be started, stopped, and reset.
  • Color Palette Generator - An application that generates a color palette based on a randomly selected color.
  • Currency Converter - An application that converts between different currencies, using a currency API.

Calculator

prompt to ChatGPT followed by the response

Describe how a calculator application works from a high level

A calculator application is a software tool that allows users to perform mathematical operations such as addition, subtraction, multiplication, and division. At a high level, here's how a calculator application works:

  1. User Input: The user enters a mathematical expression, such as "2 + 3" or "5 * 6". The expression can be entered through a keyboard, a touch screen, or a mouse.
  2. Parsing: The calculator parses the expression to determine its structure and meaning. This process involves breaking down the expression into its component parts, such as numbers, operators, and parentheses.
  3. Evaluation: The calculator evaluates the expression by carrying out the operations in the correct order. This process involves using the order of operations (e.g., performing all the multiplications and divisions before the additions and subtractions) to ensure that the expression is evaluated correctly.
  4. Result: The calculator displays the result of the evaluation to the user. This result can be displayed in decimal or fractional form, depending on the preferences of the user and the calculator.
  5. Storage: Some calculators allow users…
follow up prompt to ChatGPT followed by the response

I'm going to ask you to help build this application. Please generate all code using React and Typescript. Let's start with the UI. What's the first React component I should create?

The first component you should create is the component that represents the overall layout of the calculator, which we can call the Calculator component. This component will contain all other components for the calculator buttons and display.

Here is a basic implementation of the Calculator component in React with TypeScript:

import React, { useState } from 'react';

const Calculator: React.FC = () => {
  const [displayValue, setDisplayValue] = useState('0');

  return (
    <div className="calculator">
      <div className="display">{displayValue}</div>
      {/* Add buttons here */}
    </div>
  );
};

export default Calculator;

Calculator

Counts from bottom to top

Phone

Counts from top to bottom

The image juxtaposes two layouts – one of a calculator and one of a phone keypad. Both consist of buttons arranged in grids. The calculator has buttons with numbers, operations, and functions like AC, percentage, and equals, going from 0 at the bottom to 9 at the top. The phone keypad shows numbers from 1 to 9, letters, as well as star, hash, and a call button starting from the top down to 0 at the bottom. Each side of the image is labeled to indicate the direction in which the numbers count (bottom to top for the calculator, and top to bottom for the phone).
prompt to ChatGPT followed by the response

I have created an OperatorButton component based on the earlier NumberButton code provided, but I made the value only accept type string. Please generate the code for rendering the common mathematical operator buttons.

Sure! Here's an example of how you can render the operator buttons in the 'Calculator' component:

A simple web based calculator app UI.

How does a Calculator work?

What are the internal algorithms?

The image shows a person leaning over an open car hood, seemingly inspecting or working on the engine.

IMPROVING THE INTERNAL LOGIC

Describe the internal algorithms used by a calculator to take the input from the user and calculate the result?

The start of a detailed reply from the AI is reproduced.

Reverse Polish Notation

What is it?

Reverse Polish notation (RPN) is a method for representing expressions in which the operator symbol is placed after the arguments being operated on.

Infix Notation

RPN

An image showing a sequence of mathematical operations in Infix Notation that reads "2 times 3 plus 4 times 5" represented by colored buttons with numbers and operations symbols. The algorithm is animated and Lachlan describes this is detail

Shunting Yard Algorithm

What is it?

A method for parsing arithmetical or expressions specified in infix notation. It can produce a postfix notation string, also known as Reverse Polish Notation (RPN)

How it works

An animation of the shunting yard algorithm plays. Lachlan describes it.

Here is an implementation of the Shunting Yard Algorithm in JavaScript:

The start of the generated algorithm is reproduced.

The function to evaluate the result of the equation in RPN notation is known as the "Reverse Polish Notation evaluation algorithm".

Here's the implementation in JavaScript:

The start of the generated algorithm is reproduced.

Testing RPN Conversion

The Result

An animation showing the algorithm in action. Initially it leads to buggy output.

Here's an updated version of the convertToRPN function to address this issue:

Shows a reproduction of part of the updated algorithm.

can you write the precedence function too?

Sure! Here is a precedence function that takes in an operator symbol and returns an integer value representing the operator's precedence:

Shows a reproduction of the precedence function.

Fixed Algorithm

Shows an animation of the algorithm now functioning properly.
The image shows a simple calculator application interface on a browser window with the title "React App" visible on the tab.