Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Types? 
3.
Choice Types in Carbon
4.
Frequently Asked Questions
4.1.
When did Carbon language get introduced?
4.2.
Is Carbon language Bi-directional?
4.3.
Is Carbon language an open source?
4.4.
Is Carbon language an interpreted language?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Choice Types in Carbon

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Carbon is an open-source, statically typed, compiled programming language developed by Google to replace C++. Carbon provides developers with modern programming practices such as generics, modular code organization, and simple syntax. Carbon is still an experiment in its early stages. Having said that, many features that will assist you in writing the Carbon code you'll love have yet to be added.

So, what’s new in this article? 

Choice types in carbon

In this article, we will discuss Choice Types in Carbon, yet another powerful feature of the Carbon programming language.

Click on the following link to read further: Features of C Language

What are Types? 

In simple terms, a type is a set of possible values. 

  • Boolean means that only True or False can be used. 
  • Integer means that only whole numbers between 232 and (-232)+1 can be used. 


Types may have other functions, such as describing how to construct data in memory and what we can do with it, but at its core, a type defines what values are allowed.

Now, this constraint is enforced at compilation time in statically-typed compiled languages like Carbon which greatly aids in ensuring the correctness and reliability of the program. Additionally, it greatly improves code readability and makes it more comprehensive.

The types we can use are fundamentally linked to the type system of a programming language, so we are at the mercy of the programming language in terms of how precisely we can specify what possible values can be in a given type.

So, what are Choice Types in Carbon? 

how

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Choice Types in Carbon

A choice type is a tagged union that can hold various data types in the largest storage area. Now, what is a tagged union

union

In many older languages, a "union" type represents "a collection of exclusive alternative types." 

For instance, if you have a variable that can sometimes represent a value of type A and sometimes a value of type B, you can represent it as a union type (A U B). If we consider A and B to be two distinct sets of values, then any given value in (A U B) comes from either A or B.

Older and less sophisticated languages used to have type systems that directly reflected memory layout. C is one example. In a C program, a "union" type is given a memory layout that "overlaps" the memory layouts of A and B. For example, if you have a union of a 16-bit int and a 64-bit pointer to an integer, the compiler will use 64 bits (max(16,64)) to represent the union type. 

The problem is that you need to know whether the value in the location is a 16-bit integer or a 64-bit pointer. 

Now how to differentiate between them?

how

A "tag" must be added to the type to differentiate between these two cases. 

Assume the tag is 8 bits long. The union type now carries 64+8 bits, with the extra 8 bits indicating which specific type is carried in the value. 

In simple words, it can be thought of as a type with several "cases," each of which must be handled correctly when that type is manipulated.

cases

Let us now see the Implementation of the Choice Types in Carbon:

A choice type is identified by a name and a list of cases separated by commas (,). Each case has a name and a list of optional parameters.

The choice keyword is followed by the type's name and a list of alternatives enclosed in curly braces to form a choice declaration.

choice Result {
  Success(value: i32),
  Failure(error: String),
  Cancelled
}

how

The value of a choice type is one of the cases plus the values of the case's parameters, if any. A value can be created by naming the case and providing values for any parameters like shown below: 

package ExplorerTest api;

choice Result {
  Success(value: i32),
  Failure(error: String),
  Cancelled
}

fn ParseAsInt(s: String) -> Result {
  var r: i32 = 0;
  if(s == "CodingNinjas"){
      return .Success(r);
  }
   return .Failure("Invalid character");
}

fn Main() -> i32 {
    Print(ParseAsInt("CodingNinjas"));
    return 0;
}

Output

output


Explanation: The above code snippet takes a string as a parameter and applies a for loop to check whether the string provided contains the digits. If any character is found not to be a digit, then return an Invalid character. Else, return r on success.

Now, a match statement can be used to consume choice type values. 

What is a match statement? 

The match is a control flow that is similar to a switch in C and C++. The match keyword is followed by an expression enclosed in parentheses, the value of which is compared to the case declarations.

Let us implement to understand it: 

package ExplorerTest api;

fn TheMatcher() -> String {
  Print("I am here");
  var x: i32 = 0;
  match (x) {
    case (0) => {
      return "Matching zero";
    }
    case (1) => {
      return "Matching one";
    }
    case (2) => {
      return "Matching two";
    }
    default => {
      return "Matching none";
    }
  }
}
fn Main() -> i32 {
    Print(TheMatcher());
    return 0;
}

Output

output


Explanation: Same as switch statement we have been studying in C or C++, here in Carbon, match plays the same role. 

Frequently Asked Questions

When did Carbon language get introduced?

Carbon language was introduced in July 2022 by a Google engineer.

Is Carbon language Bi-directional?

Carbon language is Bi-directional as it allows us to call C++ language code from Carbon and also Carbon language code to C++.

Is Carbon language an open source?

Carbon Language is an open-source language.

Is Carbon language an interpreted language?

Carbon Language is a byte-code-interpreted language.

Conclusion

To conclude the discussion, we explored Choice Types in Carbon Language. We have extensively discussed about tagged union in carbon and its importance. At last we also looked at the match statement. 

If you like to enhance your knowledge on Carbon language, you can check out our other articles-

👉 Data types in Carbon

👉 Variables in Carbon

👉 Strings in Carbon

👉 Data Types in C++

You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practise and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questionsand the Ultimate guide path for interviews. Do upvote our blog to help other ninjas grow. 

Live masterclass