A New Way to Write C
libCello 是一个能让你用高级语法糖来写C的类库。
- 接口,让你可以进行结构化设计
- 鸭子类型,允许泛型函数
- 异常控制,错误处理
- 构造器和析构器,解决内存管理问题
- 语法糖,增加代码可读性
- 基于C,意味着出色的性能和极佳的兼容性
/* Example libCello Program */ #include "Cello.h" int main(int argc, char** argv) { /* Stack objects are created using "$" */ var int_item = $(Int, 5); var float_item = $(Real, 2.4); var string_item = $(String, "Hello"); /* Heap objects are created using "new" */ var items = new(List, int_item, float_item, string_item); /* Collections can be looped over */ foreach (item in items) { /* Types are also objects */ var type = type_of(item); print("Object %$ has type %$\n", item, type); } /* Heap objects destroyed with "delete" */ delete(items); }
快速开始
更多示例请查看快速开始章节:
- 容器和集合
- 类型和类
- 异常
- 一级函数
- 内存管理
或者关于这个项目的介绍:
- 极限改造C语言
- Cello VS C++ VS Obj-C
或者一个更长的示例:
/* Another Example Cello Program */ #include "Cello.h" int main(int argc, char** argv) { /* Tables require "Eq" and "Hash" on key type */ var prices = new(Table, String, Int); put(prices, $(String, "Apple"), $(Int, 12)); put(prices, $(String, "Banana"), $(Int, 6)); put(prices, $(String, "Pear"), $(Int, 55)); /* Tables also supports iteration */ foreach (key in prices) { var price = get(prices, key); print("Price of %$ is %$\n", key, price); } /* "with" automatically closes file at end of scope. */ with (file in open($(File, NULL), "prices.bin", "wb")) { /* First class function object */ lambda(write_pair, args) { /* Run time type-checking with "cast" */ var key = cast(at(args, 0), String); var value = cast(get(prices, key), Int); try { print_to(file, 0, "%$ :: %$\n", key, value); } catch (e in IOError) { println("Could not write to file - got %$", e); } return None; }; /* Higher order functions */ map(prices, write_pair); } delete(prices); }
灵感
Cello项目的灵感来自于Haskell,语法和语义来自于Python和Obj-C。Cello并不是C语言的面向对象变种。而是一套工具,它可以把C变成某种动态语言或强大的函数式编程语言。
虽然语法很友好,但是Cello并不适合初学者。它只适合高级C开发者,因为手动内存管理在高级概念中并不是那么显而易见。总地来说,Cello是一个有趣的实验,我们只想看看能如何极限地改造C语言。