🎯 empfohlene Sammlungen
Balanced sample collections from various categories for you to explore
Carbon Beispiele
Carbon Programmiersprachen-Beispiele - Googles C++ Nachfolger mit modernen Features und Leistung
💻 Carbon Hello World carbon
🟢 simple
⭐⭐
Carbon Hello World Programm mit fundamentaler Syntax und Sprachfeatures
⏱️ 20 min
🏷️ carbon, programming, systems, google
Prerequisites:
Basic programming concepts, C++ familiarity helpful
// Carbon Hello World Examples
// 1. Basic Hello World
package Main;
import Library;
fn Main() -> i32 {
Print("Hello, World!\n");
return 0;
}
// 2. Hello World with variables and types
fn HelloWorldWithVariables() {
// String literals and variables
var message1: String = "Hello, World!";
var message2: String = "Hello, Carbon!";
Print("{0}\n", message1);
Print("{0}\n", message2);
// Basic data types
var integer: i32 = 42;
var unsigned_integer: u32 = 100;
var floating_point: f64 = 3.14159;
var boolean: bool = true;
var character: u8 = 'A';
Print("Integer: {0}\n", integer);
Print("Unsigned: {0}\n", unsigned_integer);
Print("Float: {0}\n", floating_point);
Print("Boolean: {0}\n", boolean);
Print("Character: {0}\n", character);
}
// 3. Hello World with functions
fn SayHello() -> String {
return "Hello, World!";
}
fn GreetUser(name: String) -> String {
// String interpolation
return "Hello, {0}!".format(name);
}
fn HelloWorldWithFunctions() {
Print("{0}\n", SayHello());
Print("{0}\n", GreetUser("Carbon"));
}
// 4. Hello World with classes
class User {
var name: String;
var age: i32;
// Constructor
fn Create(n: String, a: i32) -> Self {
return {.name = n, .age = a};
}
// Method
fn Greet(self: Self) {
Print("Hello, {0}! You are {1} years old.\n", self.name, self.age);
}
}
fn HelloWorldWithClasses() {
var user = User.Create("Alice", 30);
user.Greet();
}
// 5. Hello World with generics
fn PrintAndReturn[T:! Type](value: T) -> T {
Print("Value: {0}\n", value);
return value;
}
fn HelloWorldWithGenerics() {
var int_result = PrintAndReturn(42);
var string_result = PrintAndReturn("Hello, Carbon!");
var bool_result = PrintAndReturn(true);
Print("Returned: {0}, {1}, {2}\n", int_result, string_result, bool_result);
}
// 6. Hello World with templates
template HelloString {
fn Get() -> String {
return "Hello from template!";
}
}
template HelloNumber {
fn Get() -> i32 {
return 42;
}
}
fn HelloWorldWithTemplates() {
Print("{0}\n", HelloString.Get());
Print("{0}\n", HelloNumber.Get());
}
// 7. Hello World with interfaces
interface Greetable {
fn Greet(self: Self);
}
class FriendlyUser {
extends Greetable;
var name: String;
fn Create(n: String) -> Self {
return {.name = n};
}
fn Greet(self: Self) {
Print("Friendly hello, {0}!\n", self.name);
}
}
fn HelloWorldWithInterfaces() {
var user = FriendlyUser.Create("Bob");
user.Greet();
}
// 8. Hello World with optional types
fn FindGreeting(id: i32) -> Optional(String) {
match (id) {
case 1 => { return "Hello"; }
case 2 => { return "Hola"; }
case 3 => { return "Bonjour"; }
case _ => { return {}; }
}
}
fn HelloWorldWithOptionals() {
var greeting1 = FindGreeting(1);
var greeting2 = FindGreeting(99);
match (greeting1) {
case Some(g) => { Print("Found: {0}\n", g); }
case None => { Print("Not found\n"); }
}
match (greeting2) {
case Some(g) => { Print("Found: {0}\n", g); }
case None => { Print("Using default greeting\n"); }
}
}
// 9. Hello World with pattern matching
fn DescribeNumber(n: i32) -> String {
match (n) {
case 0 => { return "Zero"; }
case 1...9 => { return "Single digit"; }
case 10...99 => { return "Two digits"; }
case _ => { return "Many digits"; }
}
}
fn HelloWorldWithPatternMatching() {
var numbers = [0, 5, 15, 123];
for (var n in numbers) {
Print("{0}: {1}\n", n, DescribeNumber(n));
}
}
// 10. Hello World with error handling
class GreetingError {
var message: String;
fn Create(msg: String) -> Self {
return {.message = msg};
}
}
fn CreateGreeting(name: String, age: i32) -> Result(String, GreetingError) {
if (name.empty()) {
return Error(GreetingError.Create("Empty name"));
}
if (age <= 0) {
return Error(GreetingError.Create("Invalid age"));
}
return Ok("Hello, {0} (age {1})!".format(name, age));
}
fn HelloWorldWithErrorHandling() {
var result1 = CreateGreeting("Alice", 25);
var result2 = CreateGreeting("", 30);
match (result1) {
case Ok(greeting) => { Print("Success: {0}\n", greeting); }
case Error(err) => { Print("Error: {0}\n", err.message); }
}
match (result2) {
case Ok(greeting) => { Print("Success: {0}\n", greeting); }
case Error(err) => { Print("Error: {0}\n", err.message); }
}
}
// 11. Hello World with collections
fn HelloWorldWithCollections() {
// Array
var greetings: [String] = ["Hello", "Hola", "Bonjour", "Ciao"];
Print("Array greetings:\n");
for (var greeting in greetings) {
Print("{0}, World!\n", greeting);
}
// Vector (dynamic array)
var dynamic_greetings: Vector(String) = {};
dynamic_greetings.append("Hi");
dynamic_greetings.append("Hey");
dynamic_greetings.append("Yo");
Print("\nDynamic greetings:\n");
for (var greeting in dynamic_greetings) {
Print("{0}, World!\n", greeting);
}
// Map
var language_greetings: Map(String, String) = {};
language_greetings["english"] = "Hello";
language_greetings["spanish"] = "Hola";
language_greetings["french"] = "Bonjour";
Print("\nLanguage greetings:\n");
for (var [language, greeting] in language_greetings) {
Print("{0}: {1}\n", language, greeting);
}
}
// 12. Hello World with modern features
fn HelloWorldWithModernFeatures() {
// Auto type inference
var inferred = 42; // inferred as i32
var message = "Hello, Modern Carbon!"; // inferred as String
// Type-safe string formatting
var formatted = "{0} + {1} = {2}".format(inferred, 8, inferred + 8);
// Lambda functions
var multiplier = fn(i: i32) -> i32 { return i * 2; };
var result = multiplier(21);
// Range-based for loop
var range = 1...5;
for (var i in range) {
Print("Square of {0}: {1}\n", i, i * i);
}
Print("{0}\n", formatted);
Print("Lambda result: {0}\n", result);
}
// Main function demonstrating all examples
fn Main() -> i32 {
Print("=== Carbon Hello World Examples ===\n\n");
Print("1. Basic Hello World:\n");
HelloWorldWithVariables();
Print("\n");
Print("2. Functions:\n");
HelloWorldWithFunctions();
Print("\n");
Print("3. Classes:\n");
HelloWorldWithClasses();
Print("\n");
Print("4. Generics:\n");
HelloWorldWithGenerics();
Print("\n");
Print("5. Templates:\n");
HelloWorldWithTemplates();
Print("\n");
Print("6. Interfaces:\n");
HelloWorldWithInterfaces();
Print("\n");
Print("7. Optionals:\n");
HelloWorldWithOptionals();
Print("\n");
Print("8. Pattern Matching:\n");
HelloWorldWithPatternMatching();
Print("\n");
Print("9. Error Handling:\n");
HelloWorldWithErrorHandling();
Print("\n");
Print("10. Collections:\n");
HelloWorldWithCollections();
Print("\n");
Print("11. Modern Features:\n");
HelloWorldWithModernFeatures();
Print("\n");
Print("=== All Carbon Examples Completed ===\n");
return 0;
}
💻 Carbon Typsystem carbon
🟡 intermediate
⭐⭐⭐⭐
Fortgeschrittenes Carbon Typsystem, Speichersicherheit und moderne Sprachfeatures
⏱️ 30 min
🏷️ carbon, types, generics, memory-safety
Prerequisites:
Carbon basic syntax, Understanding of type systems
// Carbon Type System and Advanced Features
package Main;
import Library;
// 1. Type declarations and aliases
type UserID = u64;
type ProductID = u32;
type Price = f64;
struct Product {
var id: ProductID;
var name: String;
var price: Price;
var user_id: UserID;
}
fn TypeDeclarations() {
var product: Product = {
.id = 1001,
.name = "Laptop",
.price = 999.99,
.user_id = 12345
};
Print("Product: {0}, Price: {1}, User ID: {2}\n",
product.name, product.price, product.user_id);
}
// 2. Smart pointers and memory safety
interface IDisposable {
fn Dispose(self: Self);
}
class SmartPointer(T:! Type) {
extends IDisposable;
var ptr: *T;
var allocated: bool;
// Constructor
fn Create(ptr: *T) -> Self {
return {
.ptr = ptr,
.allocated = true
};
}
// Destructor
fn Dispose(self: Self) {
if (self.allocated) {
// In real Carbon, this would deallocate memory
Print("Deallocating smart pointer\n");
self.allocated = false;
}
}
// Dereference operator
fn opDereference(self: Self) -> *T {
return self.ptr;
}
}
fn SmartPointers() {
var value: i32 = 42;
var smart_ptr = SmartPointer(i32).Create(&value);
Print("Value via smart pointer: {0}\n", *smart_ptr);
// Automatic cleanup when smart_ptr goes out of scope
smart_ptr.Dispose();
}
// 3. Pattern matching advanced features
enum NetworkResponse(T:! Type) {
Success(T),
Error(ErrorCode, String),
Timeout,
NetworkUnavailable
}
enum ErrorCode {
NotFound,
PermissionDenied,
ServerError,
InvalidInput
}
fn ProcessNetworkResponse[T:! Type](response: NetworkResponse(T)) {
match (response) {
case NetworkResponse.Success(data) => {
Print("Request succeeded with data: {0}\n", data);
}
case NetworkResponse.Error(code, message) => {
Print("Request failed with error {0}: {1}\n", code, message);
}
case NetworkResponse.Timeout => {
Print("Request timed out\n");
}
case NetworkResponse.NetworkUnavailable => {
Print("Network is unavailable\n");
}
}
}
fn AdvancedPatternMatching() {
var success_response = NetworkResponse(String).Success("Data received");
var error_response = NetworkResponse(String).Error(
ErrorCode.NotFound, "Resource not found"
);
var timeout_response = NetworkResponse(String).Timeout;
ProcessNetworkResponse(success_response);
ProcessNetworkResponse(error_response);
ProcessNetworkResponse(timeout_response);
}
// 4. Generics and constraints
interface Comparable {
fn Compare(self: Self, other: Self) -> Ordering;
}
enum Ordering {
Less,
Equal,
Greater
}
class Number {
extends Comparable;
var value: f64;
fn Create(v: f64) -> Self {
return {.value = v};
}
fn Compare(self: Self, other: Self) -> Ordering {
if (self.value < other.value) { return Ordering.Less; }
if (self.value == other.value) { return Ordering.Equal; }
return Ordering.Greater;
}
fn opLessThan(self: Self, other: Self) -> bool {
return self.Compare(other) == Ordering.Less;
}
fn opGreaterThan(self: Self, other: Self) -> bool {
return self.Compare(other) == Ordering.Greater;
}
}
fn FindMax[T:! Comparable](arr: [T]) -> Optional(T) {
if (arr.empty()) {
return {};
}
var max_val = arr[0];
for (var i = 1; i < arr.size(); ++i) {
if (arr[i] > max_val) {
max_val = arr[i];
}
}
return max_val;
}
fn GenericsAndConstraints() {
var numbers: [Number] = {
Number.Create(3.14),
Number.Create(1.41),
Number.Create(2.71),
Number.Create(1.618)
};
match (FindMax(numbers)) {
case Some(max_num) => {
Print("Maximum value: {0}\n", max_num.value);
}
case None => {
Print("Empty array\n");
}
}
}
// 5. Template metaprogramming
template IsIntegral(T:! Type) {
const value: bool = T == i8 || T == i16 || T == i32 || T == i64 ||
T == u8 || T == u16 || T == u32 || T == u64;
}
template EnableIf(T:! Type, condition: bool) {
extern if (condition);
}
template Square(T:! Type) {
extern if IsIntegral(T).value;
fn Square(x: T) -> T {
return x * x;
}
}
template Square(i32) {
fn Square(x: i32) -> i32 {
// Specialized version for i32
Print("Using specialized i32 square\n");
return x * x;
}
}
fn TemplateMetaprogramming() {
var i_result = Square(42);
// var f_result = Square(3.14); // Compile error: not integral
Print("Square of 42: {0}\n", i_result);
}
// 6. Advanced error handling with custom error types
class DatabaseError {
var code: i32;
var message: String;
var details: Optional(String);
fn Create(c: i32, msg: String, det: Optional(String)) -> Self {
return {
.code = c,
.message = msg,
.details = det
};
}
fn Format(self: Self) -> String {
match (self.details) {
case Some(details) => {
return "Error {0}: {1} - {2}".format(self.code, self.message, details);
}
case None => {
return "Error {0}: {1}".format(self.code, self.message);
}
}
}
}
fn QueryDatabase(query: String) -> Result(String, DatabaseError) {
if (query.empty()) {
return Error(DatabaseError.Create(400, "Empty query", Some("Query cannot be empty")));
}
if (query.contains("DROP")) {
return Error(DatabaseError.Create(403, "Forbidden operation",
Some("DROP commands are not allowed")));
}
// Simulate successful query
return Ok("Query executed successfully");
}
fn AdvancedErrorHandling() {
var queries = ["SELECT * FROM users", "DROP TABLE users", ""];
for (var query in queries) {
var result = QueryDatabase(query);
match (result) {
case Ok(success) => {
Print("Query '{0}': {1}\n", query, success);
}
case Error(db_error) => {
Print("Query '{0}': {1}\n", query, db_error.Format());
}
}
}
}
// 7. Lambda functions and functional programming
fn FunctionalProgramming() {
// Lambda with capture
var multiplier = 3;
var multiply_fn = fn(x: i32) -> i32 { return x * multiplier; };
// Lambda as parameter
fn ApplyOperation(arr: [i32, 5], operation: fn(i32) -> i32) -> [i32, 5] {
var result: [i32, 5] = {};
for (var i = 0; i < arr.size(); ++i) {
result[i] = operation(arr[i]);
}
return result;
}
var numbers: [i32, 5] = {1, 2, 3, 4, 5};
var doubled = ApplyOperation(numbers, fn(x: i32) -> i32 { return x * 2; });
var multiplied = ApplyOperation(numbers, multiply_fn);
Print("Original: {0}\n", numbers);
Print("Doubled: {0}\n", doubled);
Print("Multiplied by 3: {0}\n", multiplied);
}
// 8. Modules and namespaces
module Math {
fn Add(a: f64, b: f64) -> f64 {
return a + b;
}
fn Multiply(a: f64, b: f64) -> f64 {
return a * b;
}
module Advanced {
fn Power(base: f64, exp: i32) -> f64 {
if (exp == 0) { return 1.0; }
if (exp < 0) { return 1.0 / Power(base, -exp); }
return base * Power(base, exp - 1);
}
}
}
fn ModulesAndNamespaces() {
var sum = Math.Add(3.14, 2.71);
var product = Math.Multiply(4.2, 1.5);
var power = Math.Advanced.Power(2.0, 8);
Print("Sum: {0}, Product: {1}, Power: {2}\n", sum, product, power);
}
// 9. Reflection capabilities (conceptual)
interface Reflectable {
fn GetType() -> String;
fn GetFields() -> [String];
fn GetFieldValue(self: Self, field: String) -> String;
}
class ReflectableUser {
extends Reflectable;
var name: String;
var age: i32;
var email: String;
fn Create(n: String, a: i32, e: String) -> Self {
return {
.name = n,
.age = a,
.email = e
};
}
fn GetType() -> String {
return "ReflectableUser";
}
fn GetFields() -> [String] {
return {"name", "age", "email"};
}
fn GetFieldValue(self: Self, field: String) -> String {
match (field) {
case "name" => { return self.name; }
case "age" => { return "{0}".format(self.age); }
case "email" => { return self.email; }
case _ => { return "Unknown field"; }
}
}
}
fn PrintReflectionInfo[T:! Reflectable](obj: T) {
Print("Type: {0}\n", obj.GetType());
Print("Fields:\n");
for (var field in obj.GetFields()) {
Print(" {0}: {1}\n", field, obj.GetFieldValue(field));
}
}
fn Reflection() {
var user = ReflectableUser.Create("Alice", 30, "[email protected]");
PrintReflectionInfo(user);
}
// 10. Async/await concepts (future Carbon feature)
class Future(T:! Type) {
var value: Optional(T);
var completed: bool;
fn Create() -> Self {
return {
.value = {},
.completed = false
};
}
fn Set(self: Self, val: T) {
self.value = val;
self.completed = true;
}
fn Await(self: Self) -> T {
while (!self.completed) {
// In real implementation, this would yield to scheduler
// Simulated busy wait for demonstration
}
return self.value.unwrap();
}
}
fn AsyncConcepts() {
var future_int = Future(i32).Create();
var future_string = Future(String).Create();
// Simulate async operations
future_int.Set(42);
future_string.Set("Async result");
Print("Async int result: {0}\n", future_int.Await());
Print("Async string result: {0}\n", future_string.Await());
}
// Main function demonstrating all advanced features
fn Main() -> i32 {
Print("=== Carbon Type System and Advanced Features ===\n\n");
Print("1. Type Declarations:\n");
TypeDeclarations();
Print("\n");
Print("2. Smart Pointers:\n");
SmartPointers();
Print("\n");
Print("3. Advanced Pattern Matching:\n");
AdvancedPatternMatching();
Print("\n");
Print("4. Generics and Constraints:\n");
GenericsAndConstraints();
Print("\n");
Print("5. Template Metaprogramming:\n");
TemplateMetaprogramming();
Print("\n");
Print("6. Advanced Error Handling:\n");
AdvancedErrorHandling();
Print("\n");
Print("7. Functional Programming:\n");
FunctionalProgramming();
Print("\n");
Print("8. Modules and Namespaces:\n");
ModulesAndNamespaces();
Print("\n");
Print("9. Reflection:\n");
Reflection();
Print("\n");
Print("10. Async Concepts:\n");
AsyncConcepts();
Print("\n");
Print("=== All Advanced Features Completed ===\n");
return 0;
}
💻 Carbon Leistung und Interop carbon
🔴 complex
⭐⭐⭐⭐⭐
Carbon Leistungsoptimierung und C++ Interoperabilität
⏱️ 35 min
🏷️ carbon, performance, systems, interop
Prerequisites:
Advanced Carbon syntax, C++ knowledge, Performance optimization concepts
// Carbon Performance and C++ Interoperability
package Main;
import CppLibrary; // Hypothetical C++ interop library
import Library;
// 1. Performance-critical data structures
class PerformanceVector(T:! Type) {
var data: *T;
var size: u64;
var capacity: u64;
fn Create(initial_capacity: u64) -> Self {
return {
.data = Allocate(T, initial_capacity),
.size = 0,
.capacity = initial_capacity
};
}
fn Dispose(self: Self) {
Deallocate(self.data);
}
fn Append(self: Self, item: T) {
if (self.size >= self.capacity) {
// Double capacity with efficient reallocation
var new_capacity = self.capacity * 2;
var new_data = Allocate(T, new_capacity);
// Fast memory copy
for (var i = 0; i < self.size; ++i) {
new_data[i] = self.data[i];
}
Deallocate(self.data);
self.data = new_data;
self.capacity = new_capacity;
}
self.data[self.size] = item;
self.size += 1;
}
fn opIndex(self: Self, index: u64) -> *T {
return &self.data[index];
}
fn Size(self: Self) -> u64 {
return self.size;
}
fn Capacity(self: Self) -> u64 {
return self.capacity;
}
}
fn PerformanceDataStructures() {
var vec = PerformanceVector(i32).Create(4);
// Efficient bulk insertion
for (var i = 0; i < 1000; ++i) {
vec.Append(i * 2);
}
Print("Vector size: {0}, capacity: {1}\n", vec.Size(), vec.Capacity());
Print("Element 500: {0}\n", *vec[500]);
vec.Dispose();
}
// 2. Memory pool allocator for performance
class MemoryPool {
var pool: *u8;
var pool_size: u64;
var used: u64;
var allocations: u64;
fn Create(size: u64) -> Self {
return {
.pool = Allocate(u8, size),
.pool_size = size,
.used = 0,
.allocations = 0
};
}
fn Dispose(self: Self) {
Deallocate(self.pool);
}
fn Allocate(T:! Type)(self: Self, count: u64 = 1) -> *T {
var size = count * sizeof(T);
var aligned_size = ((size + 7) / 8) * 8; // 8-byte alignment
if (self.used + aligned_size > self.pool_size) {
return null; // Pool exhausted
}
var ptr = self.pool + self.used;
self.used += aligned_size;
self.allocations += 1;
return ptr as *T;
}
fn Reset(self: Self) {
self.used = 0;
self.allocations = 0;
}
fn Usage(self: Self) -> f64 {
return (self.used as f64) / (self.pool_size as f64);
}
}
fn MemoryPoolPerformance() {
var pool = MemoryPool.Create(1024 * 1024); // 1MB pool
// Fast allocation from pool
var int_array = pool.Allocate(i32, 1000);
var string_ptr = pool.Allocate(String);
Print("Pool usage: {0:.2f}%\n", pool.Usage() * 100);
Print("Allocations: {0}\n", pool.allocations);
// Reset pool for reuse
pool.Reset();
Print("Pool usage after reset: {0:.2f}%\n", pool.Usage() * 100);
pool.Dispose();
}
// 3. SIMD vectorization support
extern "C++" {
// SIMD intrinsics interface
fn simd_add_f32(a: *f32, b: *f32, result: *f32, count: u64);
fn simd_mul_f32(a: *f32, b: *f32, result: *f32, count: u64);
fn simd_dot_f32(a: *f32, b: *f32, result: *f32, count: u64);
}
class SIMDVector {
var data: *f32;
var size: u64;
fn Create(n: u64) -> Self {
return {
.data = Allocate(f32, n),
.size = n
};
}
fn Dispose(self: Self) {
Deallocate(self.data);
}
fn Set(self: Self, index: u64, value: f32) {
self.data[index] = value;
}
fn Get(self: Self, index: u64) -> f32 {
return self.data[index];
}
fn Add(self: Self, other: Self, result: Self) {
simd_add_f32(self.data, other.data, result.data, self.size);
}
fn Multiply(self: Self, other: Self, result: Self) {
simd_mul_f32(self.data, other.data, result.data, self.size);
}
fn DotProduct(self: Self, other: Self) -> f64 {
var result: f32 = 0.0;
simd_dot_f32(self.data, other.data, &result, self.size);
return result as f64;
}
}
fn SIMDPerformance() {
var size = 1024; // Must be multiple of SIMD width
var vec1 = SIMDVector.Create(size);
var vec2 = SIMDVector.Create(size);
var result = SIMDVector.Create(size);
// Initialize vectors
for (var i = 0; i < size; ++i) {
vec1.Set(i, i as f32);
vec2.Set(i, (i * 2) as f32);
}
// SIMD operations
vec1.Add(vec2, result);
var dot = vec1.DotProduct(vec2);
Print("SIMD Add result[0]: {0}\n", result.Get(0));
Print("SIMD Add result[1023]: {0}\n", result.Get(1023));
Print("SIMD Dot product: {0}\n", dot);
vec1.Dispose();
vec2.Dispose();
result.Dispose();
}
// 4. C++ interoperability examples
extern "C++" {
// C++ standard library types
cpp_class std.vector(T) {
fn size() -> u64;
fn push_back(value: T);
fn operator[](index: u64) -> T;
fn data() -> *T;
}
cpp_class std.string {
fn c_str() -> *char;
fn size() -> u64;
}
// Custom C++ class
cpp_class CppCalculator {
fn Create() -> Self;
fn Add(a: f64, b: f64) -> f64;
fn Multiply(a: f64, b: f64) -> f64;
fn GetHistory() -> std.vector(f64);
}
}
fn CppInterop() {
// Use C++ std::vector
var cpp_vec = std.vector(i32).Create();
cpp_vec.push_back(42);
cpp_vec.push_back(84);
Print("C++ vector size: {0}\n", cpp_vec.size());
Print("C++ vector[0]: {0}\n", cpp_vec[0]);
// Use C++ std::string
var cpp_str = std.string.Create("Hello from C++");
Print("C++ string: {0}\n", cpp_str.c_str());
// Use custom C++ class
var calc = CppCalculator.Create();
var sum = calc.Add(3.14, 2.71);
var product = calc.Multiply(4.2, 1.5);
Print("C++ Calculator - Sum: {0}, Product: {1}\n", sum, product);
var history = calc.GetHistory();
Print("Calculator history size: {0}\n", history.size());
}
// 5. Zero-cost abstractions
template Container(T:! Type) {
fn Map(arr: [T], operation: fn(T) -> T) -> [T] {
var result: [T] = {};
for (var item in arr) {
result.push(operation(item));
}
return result;
}
fn Filter(arr: [T], predicate: fn(T) -> bool) -> [T] {
var result: [T] = {};
for (var item in arr) {
if (predicate(item)) {
result.push(item);
}
}
return result;
}
fn Reduce(arr: [T], initial: T, operation: fn(T, T) -> T) -> T {
var result = initial;
for (var item in arr) {
result = operation(result, item);
}
return result;
}
}
fn ZeroCostAbstractions() {
var numbers = [1, 2, 3, 4, 5];
// These compile to highly optimized code
var doubled = Container(i32).Map(numbers, fn(x: i32) -> i32 { return x * 2; });
var evens = Container(i32).Filter(numbers, fn(x: i32) -> bool { return x % 2 == 0; });
var sum = Container(i32).Reduce(numbers, 0, fn(acc: i32, x: i32) -> i32 { return acc + x; });
Print("Doubled: {0}\n", doubled);
Print("Evens: {0}\n", evens);
Print("Sum: {0}\n", sum);
}
// 6. Compile-time computations
const Fib(n: u32) = n <= 1 ? n : Fib(n - 1) + Fib(n - 2);
template CompileTimeFib(n: u32) {
const value = Fib(n);
}
fn CompileTimeComputations() {
// Compile-time Fibonacci values
const fib10 = CompileTimeFib(10).value;
const fib20 = CompileTimeFib(20).value;
Print("Fib(10) = {0} (computed at compile time)\n", fib10);
Print("Fib(20) = {0} (computed at compile time)\n", fib20);
// Compile-time string operations
const greeting = "Hello, Carbon!";
const greeting_length = greeting.size();
Print("Greeting: {0}\n", greeting);
Print("Length: {0} (computed at compile time)\n", greeting_length);
}
// 7. Performance measurement utilities
class Timer {
var start_time: u64;
var end_time: u64;
fn Create() -> Self {
return {
.start_time = 0,
.end_time = 0
};
}
fn Start(self: Self) {
self.start_time = GetCurrentTimeNanos();
}
fn Stop(self: Self) {
self.end_time = GetCurrentTimeNanos();
}
fn ElapsedNanos(self: Self) -> u64 {
return self.end_time - self.start_time;
}
fn ElapsedMillis(self: Self) -> f64 {
return (self.ElapsedNanos() as f64) / 1_000_000.0;
}
fn ElapsedSeconds(self: Self) -> f64 {
return (self.ElapsedNanos() as f64) / 1_000_000_000.0;
}
}
extern "C++" {
fn GetCurrentTimeNanos() -> u64;
}
fn PerformanceMeasurement() {
var timer = Timer.Create();
// Measure allocation performance
timer.Start();
var pool = MemoryPool.Create(10 * 1024 * 1024); // 10MB
for (var i = 0; i < 100_000; ++i) {
var ptr = pool.Allocate(i64);
if (ptr != null) {
*ptr = i;
}
}
timer.Stop();
Print("100k allocations from pool: {0:.3f} ms\n", timer.ElapsedMillis());
Print("Pool usage: {0:.2f}%\n", pool.Usage() * 100);
pool.Dispose();
}
// 8. Parallel processing concepts
class ThreadPool {
var threads: *Thread;
var thread_count: u64;
var work_queue: WorkQueue;
fn Create(count: u64) -> Self {
return {
.threads = Allocate(Thread, count),
.thread_count = count,
.work_queue = WorkQueue.Create()
};
}
fn Dispose(self: Self) {
// Wait for all threads to finish
// Clean up resources
Deallocate(self.threads);
}
fn SubmitWork(self: Self, work: fn()) -> Future(void) {
// Submit work to queue and return future
// Implementation would involve thread synchronization
}
}
fn ParallelProcessing() {
var pool = ThreadPool.Create(4);
// Parallel computation example
var results = [Future(void)]{};
for (var i = 0; i < 8; ++i) {
var future = pool.SubmitWork(fn() {
// Simulate work
Print("Work item {0} executing\n", i);
});
results.push(future);
}
// Wait for all work to complete
for (var future in results) {
future.Await();
}
pool.Dispose();
}
// Main function demonstrating all performance features
fn Main() -> i32 {
Print("=== Carbon Performance and Interop Examples ===\n\n");
Print("1. Performance Data Structures:\n");
PerformanceDataStructures();
Print("\n");
Print("2. Memory Pool Performance:\n");
MemoryPoolPerformance();
Print("\n");
Print("3. SIMD Performance:\n");
SIMDPerformance();
Print("\n");
Print("4. C++ Interoperability:\n");
CppInterop();
Print("\n");
Print("5. Zero-Cost Abstractions:\n");
ZeroCostAbstractions();
Print("\n");
Print("6. Compile-Time Computations:\n");
CompileTimeComputations();
Print("\n");
Print("7. Performance Measurement:\n");
PerformanceMeasurement();
Print("\n");
Print("8. Parallel Processing:\n");
ParallelProcessing();
Print("\n");
Print("=== All Performance Examples Completed ===\n");
return 0;
}