写在前面的:
本节我们就要结束类型的学习了。就剩下三个方式了:Struct, Type Alias, Type Expressions。其中我们会涉及一些比较新的概念:C FFI(Foreign Function Interface):https://tutorial.ponylang.io/c-ffi.html、Union/Intersection Type。
1.Structs:
你不会经常用到Struct的,why?因为它是用来沟通Pony语言和C语言的。除此之外,它和类别无二样:
A
struct
is a class like mechanism used to pass data back and forth with C code via Pony’s Foreign Function Interface.Like classes, Pony structs can contain both fields and methods. Unlike classes, Pony structs have the same binary layout as C structs and can be transparently used in C functions. Structs do not have a type descriptor, which means they cannot be used in algebraic types or implement traits/interfaces.
把关键字class换成关键字struct后,一切class的规则都可以套用,此处不再赘言。我们以后在讲C FFI时,会来一个overview和further study。
2.Type Alias:
先来翻译一下:alias n.别名,假名,又名。
我们前面说过,原类有一个用途是记号。请看下面这段代码:
primitive Red
primitive Blue
primitive Green
type Color is (Red | Blue | Green)
‘|’这个运算符的含义大家都明白,||代表或运算。现在Color这个类型就可以称作是Union Type,but what's it?
A union type is a form of closed world type. That is, it says every type that can possibly be a member of it.
话回正题,type alias的标志就是关键字type,其概念的核心就是“等价”,意思是type后的新类型是(is)后面的类型。
--复合类型(Complex types):
上例子:
interface HasName
fun name(): String
interface HasAge
fun age(): U32
interface HasAddress
fun address(): String
type Person is (HasName & HasAge & HasAddress)
用&来表示的类型,我们叫intersection type。
我们再来深入理解一下:
Union type(connected by "|"):
这是一种类型集合,类型产生的实例其类型为集合元素中的一种
Intersection type(connected by "&"):
这是一种类型集合,类型产生的实例其类型为集合元素中的全部
3.Type Expressions
⭐Tuple(元组):
A tuple type is a sequence of types
我们这样定义一个元组:
var x : (String, U64)
x = ("hi", 3)
x = ("bye", 7)
可以这样赋值:
(var a, var b) = x
也可以直接访问该元组的元素:
var a = x._1
var b = x._2
Why use a tuple instead of a class? Tuples are a way to express a collection of values that doesn’t have any associated code or expected behaviour. Basically, if you just need a quick collection of things, maybe to return more than one value from a function, for example, you can use a tuple.
⭐Combining type expressions :
type Number is (Signed | Unsigned | Float)
type Signed is (I8 | I16 | I32 | I64 | I128)
type Unsigned is (U8 | U16 | U32 | U64 | U128)
type Float is (F32 | F64)
嗯哼?!
Is
Number
a type alias for a type expression that contains other type aliases? Yes! Fun, and convenient.
实际上,上述概念属于集合类型。这方面我认为Ceylon是主打,就像Pony主打并发及其数据安全。有兴趣的同学可以看看Ceylon的集合类型处理,和Pony的集合类型进行对照学习,当然Pony这部分只是实现了“现代编程语言”的一个接口,不能奢望太多。附上Ceylon网站:https://ceylon-lang.org/.对此,王垠也给出了他的意见:
写在后面的:
接下来我们会继续唠唠语法,if语句啊,for语句之类的。我打算在一篇文章里结束对Expression的介绍。总之,感谢一直以来对Pony的支持!
欢迎加入Pony语言QQ群:261824044!