MoonBit 更新
1. 支持雲原生調試功能
現在,你可以通過訪問try.moonbitlang.com,直接在瀏覽器中使用 devtools 調試 MoonBit 程序,無需安裝任何軟件。具體的使用步驟如下:
2. MoonBit 支持使用 for 關鍵字定義的函數式循環控制流
MoonBit 現在支持使用 for 關鍵字定義的函數式循環控制流,其性能接近於 C/C++ 等底層語言,比如 fib 函數可以寫成如下形式:
fn fib( n : Int ) -> Int {
for i = 0, a = 1, b = 2
i < n
i = i + 1, a = b, b = a + b {
} else { b }
}
MoonBit 的 for 循環可以作為表達式返回一個值,比如上述程序中在循環結束後使用 b 作為整個 for 循環的值,也可以在 for 的循環體中通過 break 提前返回,比如:
fn exists(haystack: Array[Int], needle: Int) -> Bool {
for i = 0; i < haystack.length(); i = i + 1 {
if haystack[i] == needle {
break true
}
} else {
false
}
}
此外,在 for 循環中可以像傳統語言一樣使用 continue 進入下一次循環,MoonBit 額外提供了帶參數的 continue 來指定下一次循環過程中循環變量的值,比如:
fn find_in_sorted[T](xs: Array[(Int, T)], i: Int) -> Option[T] {
for l = 0, r = xs.length() - 1; l < r; {
let mid = (l + r) / 2
let k = xs[mid].0
if k == i {
break Some(xs[mid].1)
} else if k > i {
continue l, mid
} else {
continue mid + 1, r
}
} else {
None
}
}
在不需要返回值的情況下,else 分支可以省略,比如:
fn print_from_0_to(n: Int) {
for i = 0; i <= n; i = i + 1 {
println(i)
}
}
3. Inline test 改進
測試的返回類型從Unit改成了Result[Unit,String],用於表示測試的結果:
test "id" {
if (id(10) != 10) { return Err("The implementation of `id` is incorrect.") }
}
編譯器會自動將test "id" {...} 的語句塊{...}使用Ok()包裹起來。因此,當語句塊的類型為Unit並且沒有提前return時,表示inline test測試通過。配合問號操作符,可以讓測試變得更加優雅:
fn id(x : Int) -> Int {
x + 1 // incorrect result
}
fn assert(x : Bool, failReason : String) -> Result[Unit,String] {
if x { Ok(()) } else { Err(failReason) }
}
test "id" {
assert(id(10) == 10, "The implementation of `id` is incorrect.")?
}
執行moon test,輸出如下:
➜ my-project moon test
running 1 tests in package username/hello/lib
test username/hello/lib::hello ... ok
test result: 1 passed; 0 failed
running 1 tests in package username/hello/main
test username/hello/main::id ... FAILED: The implementation of `id` is incorrect.
test result: 0 passed; 1 failed
Hello, world!
4. 改進 VS Code 插件的函數簽名提示,現在會顯示參數名:
5. 改進了 VS Code 插件對 core 包開發的支持
6. moon new 支持快速創建新項目
moon new hello在文件夾hello中創建一個名為username/hello的可執行項目moon new hello --lib在文件夾hello中創建一個名為username/hello的模塊