Functions in Carbon Language

Total
0
Shares
functions in carbon language
Table of Contents Hide
  1. Introduction
  2. Code Example –
  3. Conclusion

Functions in carbon language has the same role as in C, Php or any other functional language. It is used to separate a functionality for reuse. For example, a function to add two numbers.

Introduction

The carbon function structure is like this –

fn function_name (parameters) -> return_type {}

Here,

  • fn – Indicates that the entity is a function.
  • function_name – Name of your function.
  • parameters – Comma separated list of parameters along with their types.
  • return_type – Data type of the value which the function will return. Skip it if function is not returning anything.

Code Example –

fn multiply (x: i32, y: i32) -> i64 {
    return x * y;
}

Here we created a function to multiply two 32 bit integers which will result in a 64 bit integer. So, the return type is i64.

Let’s see another example –

package Sorting api;

fn Partition[T:! Comparable & Movable](s: Slice(T))
 -> i64 {
  var i: i64 = -1;

  for (e: T in s) {
    if (e <= s.Last()) {
      ++i;
      Swap(&s[i], &e);
    }
  }
  return i;
}

fn QuickSort[T:! Comparable & Movable](s: Slice(T)) {
  if (s.Size() <= 1) {
    return;
  }
  let p: i64 = Partition(s);
  QuickSort(s[:p - 1]);
  QuickSort(s[p + 1:]);
}

This example is an implementation of QuickSort algorithm. Code credit goes to Carbon team.

Conclusion

Functions in Carbon is an essential tool for modularizing the code for reuse and refactoring. The basic functionality is similar to the functions provided by any functional language.