仓颉编程语言编程技巧-模式匹配
什么是模式匹配
仓颉编程语言中支持使用模式匹配表达式(match 表达式)实现模式匹配(pattern matching),允许开发者使用更精简的代码描述复杂的分支控制逻辑。直观上看,模式描述的是一种结构,这个结构定义了一个与之匹配的实例集合,模式匹配就是去判断给定的实例是否属于模式定义的实例集合。显然,匹配的结果只有两种:匹配成功和匹配失败。match 表达式可分为两类:带 selector 的 match 表达式和不带selector 的 match 表达式。
实现枚举类型的`==`操作符
package cangjie_test
main() {
println("Red==Red? ${Red==Red}")
println("Blue==Yellow? ${Blue==Yellow}")
}
enum Color {
| Red
| Yellow
| Blue
public operator func ==(that: Color): Bool {
match ((this, that)) {
case (Red, Red) => true
case (Yellow, Yellow) => true
case (Blue, Blue) => true
case _ => false
}
}
}
输出
Red==Red? true
Blue==Yellow? false
实现类型转换
利用泛型+Option模型,推理目标类型
import std.convert.Parsable
main() {
let i: ?Int = typeConvert("0123")
println("Int: ${i}")
let f: ?Float64 = typeConvert("3.14")
println("Float64: ${f}")
let s: ?String = typeConvert("cangjie")
println("String: ${s}")
let b: ?Bool = typeConvert("true")
println("Bool: ${b}")
let o: ?Array<Int> = typeConvert("[1]")
println("Array<T>: ${o}")
}
func typeConvert<T>(str: String): ?T {
let a: ?T = None
match (a) {
case _: ?Int => Int.parse(str) as T
case _: ?Float64 => Float64.parse(str) as T
case _: ?Bool => Bool.parse(str) as T
case _: ?String => str as T
case _ => None
}
}
输出
Int: Some(123)
Float64: Some(3.140000)
String: Some(cangjie)
Bool: Some(true)
Array<T>: None