关于编程语言:MoonBit-新增-运算符引入-super-trait-和-List-字面量机制

5次阅读

共计 2219 个字符,预计需要花费 6 分钟才能阅读完成。

MoonBit 更新

1. 增加了 += 系列语句

包含 +=、-=、*=、/=,反对运算符重载:

fn init {let array = [1,2,3,4]
  array[2] *= 10
  println(array) // [1, 2, 30, 4]
}

fn init {
  let mut a = 1
  a += 20
  println(a) // 21
}
struct Foo {data : Array[Int]
} derive(Debug)

fn op_set(self : Foo, index : Int, value : Int) {self.data[index] = value
}

fn op_get(self : Foo, index : Int) -> Int {self.data[index]
}

fn init {let foo : Foo = { data: [0,0,0,0] }
  foo[2] -= 10
  debug(foo) // {data: [0, 0, -10, 0]}
}

2. 当初 toplevel 如果没有顶格会报错

如下图所示:

3. 引入 super-trait 机制

Super-trait 通过如下的语法指定:

trait A {// ...}

trait B : A { // A is a super trait of B, B is a sub trait of A
  // ...
}

能够通过 + 来指定多个 Super-trait,示意该 sub-trait 依赖这几个 super-trait:

// ...

trait B: A + Compare + Debug {
  //       ^~~ B is a sub-trait of A *and* Compare *and* Debug
  // ...
}

在应用上,能够将 sub-trait 当作 super trait 应用,然而不可能将 super-trait 当作 sub-trait 应用。目前 Compare 是 Eq 的 sub-trait,意味着实现了 Compare 的类型可能在要求 Eq 的状况下应用,所以以这两个代码为例:

trait Eq {op_equal(Self, Self) -> Bool
}

trait Compare: Eq {compare(Self, Self) -> Int
}

fn eq[X: Compare](this: X, that: X) -> Bool {this == that}
fn compare[X: Eq](this: X, that: X) -> Int {this.compare(that)
  //   ^~~~~~~ Type X has no method compare.
}

4. 增加 T::[x, y, …] 的语法

这种语法结构会被解糖成 T::from_array([x, y, …]) 的模式。这种语法使得列表等线性数据结构的初始化更加易读。

enum List[X] {
  Nil
  Cons(X, List[X])
} derive(Show, Debug)

fn List::from_array[X](array: Array[X]) -> List[X] {
  let mut list = List::Nil
  for i = array.length() - 1; i >= 0; i = i - 1 {list = Cons(array[i], list)
  }
  list
}

fn main {println(List::[1, 2, 3])
}

输入:

Cons(1, Cons(2, Cons(3, Nil)))

5. 调整主动生成的 Show 的实现的逻辑

当初它会调用 Debug 作为实现。这意味着,当初 derive(Show) 之前须要先 derive 或自行实现 Debug。Debug 的输入是 MoonBit 语法下非法的值,而 Show 能够用于输入更好看的内容。这修复了之前 derive(Show) 在有 String 的构造体上的错误行为:

struct T {x: String} derive(Show, Debug)

fn init {println({ x: "1, y: 2"})
  // 之前: {x: 1, y: 2}
  // 当初: {x: "1, y: 2"}
}

6. 目前已不反对 fn hello() = “xx” 的语法

fn hello() = “xx” 的语法目前曾经不实用了。咱们倡议用户这样写:

extern "wasm" fn hello () =
  #| ...

当初 inline stubs 只反对 wasmgc,不反对 wasm1。

7. 当初抛弃非 Unit 的值会间接报错,如果须要抛弃须要显式应用 ignore。

fn f() -> Int {ignore(3)   // Ok.
  3 |> ignore // Ok.
  3           // Err: Expr Type Mismatch: has type Int, wanted Unit
  3           // Ok, as this value is returned, not dropped
}

8. 移除了 test 作为标识符应用的反对

IDE 更新

1. 提供更好的线上 IDE Markdown 反对

  • 能够在线上 IDE 中应用 Marp 插件来查看之前古代编程思维课的内容了。
  • Markdown 中内嵌的 MoonBit 的代码块反对语法高亮。
  • 针对内嵌有 MoonBit 代码的 Markdown 文本开发了语法查看的程序,开源在:GitHub 链接。应用办法能够参考我的项目的 README。

构建零碎更新

1. 增加 main 函数的反对

  • main 只能写在 main 包(is_main: true 的包)里
  • main 包中该当有且仅有一个 main 函数
  • main 函数的执行程序在所有 init 函数之后
  • main 包中不能有 test

2. 目前能够通过 moon upgrade 降级 MoonBit 工具链的版本了。

p.s. 然而在应用之前,必须再用装置脚本装置一次:-)

3. moon check|build|run 当初默认链接到 moonbitlang/core。

立刻开启 Moonbit 语言新体验

正文完
 0