2021.5.4

Motoko笔记

Equality (==) —and by extension inequality (!=)— is structural: two values a and bare equal, a == b, whenever they have equal contents, regardless of the physical representation, or identity, of those values in memory.

例如,字符串“hello world”和“hello”#“world”是相等的,即使它们很可能由内存中的不同对象表示。

Equality is defined only on shared types or on types that don’t contain mutable fields, mutable arrays, non-shared functions, or components of generic type.

For example, we can compare arrays of objects.

let a = [ { x = 10 }, { x = 20 } ]; 
let b = [ { x = 10 }, { x = 20 } ]; 
a == b;

结果:true : Bool

Importantly, this does not compare by reference, but by value.

Subtyping:

Equality respects subtyping so { x = 10 } == { x = 10; y = 20 } returns true.

To accommodate subtyping, two values of different types are equal if they are equal at their most specific, common supertype, meaning they agree on their common structure. The compiler will warn in cases where this might lead to subtle unwanted behaviour. For example: { x = 10 } == { y = 20 } will return true because the two values get compared at the empty record type. That’s unlikely the intention, so the compiler will emit a warning here.

{ x = 10 } == { y = 20 };

警告:
stdin:1.1-1.25: warning [M0062], comparing incompatible types
{x : Nat}
and
{y : Nat}
at common supertype
{}

结果:true : Bool

Generic types:

不能声明泛型类型变量(Generic types)是共享的,因此等式只能用于非泛型类型。例如,以下表达式生成如下警告:

func eq<A>(a : A, b : A) : Bool = a == b;

警告:
stdin:1.35-1.41: warning [M0061], comparing abstract type
A/9
to itself at supertype
Any

结果:func : <A>(A, A) -> Bool

Comparing these two at the Any type means this comparison will return true no matter its arguments, so this doesn’t work as one might hope.

如果在代码中遇到这个限制,应该接受(a,a)->Bool类型的比较函数作为参数,并使用它来比较值。

让我们看一个列表成员资格测试的例子。这第一个实现不起作用:

import List "mo:base/List"; 
func contains<A>(element : A, list : List.List<A>) : Bool { 
	switch list { 
		case (?(head, tail)) 
			element == head or contains(element, tail); 
		case null 
			false; 
	}
}; 
assert(not contains(1, ?(0, null)));

警告:
stdin:6.7-6.22: warning [M0061], comparing abstract type
A/44
to itself at supertype
Any
stdin:11.1-11.36: execution error, assertion failure

此断言将trap,因为编译器在比较type A at Any which is always true.因此,只要列表中至少有一个元素,此版本的contains将始终返回true。

第二个实现展示了如何显式地接受比较函数:

import List "mo:base/List"; 
import Nat "mo:base/Nat"; 
func contains<A>(eqA : (A, A) -> Bool, element : A, list : List.List<A>) : Bool { 
	switch list { 
		case (?(head, tail)) 
			eqA(element, head) or contains(eqA, element, tail); 
		case null 
			false; 
		} 
	}; 
assert(not contains(Nat.equal, 1, ?(0, null)));

结果:() : ()

A Student on the way to full stack of Web3.