sml基本语法(二)

变量、类型、作用域

  1. 变量
  2. 类型
  3. 作用域
    ML语言的作用域是静态的、词法的(static, lexical),与C语言类似。
    声明的变量、类型的作用域具有全局的作用域(Global Scope),即剩下的代码块都是它的作用域,详细的动态作用域(Dynamic Scope)和静态作用域的区别讲解见链接
    PS:ML也支持限制地声变量和类型,即限制它们的作用域—— l e t let let语句

绑定( B i n d i n g s Bindings Bindings

  1. 类型绑定
    一般格式: t y p e type type t y p c o n 1 = t y p 1 typcon_1 = typ_1 typcon1=typ1
    eg:type float = real
    type count = int and average = real
    floattype constructor,上面type bindings语句中引入了type constructor float

可以使用 and 同时完成两个变量绑定,这种情况下不可使用正在定义的type constructor去定义其它type constructor,如下会有报错(找不到float)

type float = real and average = float
  1. 变量绑定
    一般格式: v a l val val i d e : t y p = v a l u e ide:typ =value ide:typ=value
    eg:val pi:real = 3.14
    value的类型必须和所绑定的变量一致,变量的命名即为标识符ide

声明( D e c l a r a t i o n s Declarations Declarations

声明由bindings组成,按照顺序书写(一个接一个),可用分号将它们分隔开

限制作用域

变量和自定义类型的作用域可以通过let语句和local声明(local declarations)来限制。

  1. 格式和作用
    let语句: l e t let let dec i n in in exp e n d end end
    dec的作用域限制在exp内,当exp执行完,dec即销毁
    local声明: l o c a l local local dec i n in in dec0 e n d end end

值得注意的是exp可以是命令组(E1;E2;...;En),该表达式的值为 E n E_n En的值,其他表达式的值均会被丢弃。

let
    D
in
    E1;
    E2;
    ...;
    En
end
  1. 同名变量
    覆盖原则同所有静态作用域的语言一样(如C、Java等)
val m : int = 2
val r : int =
	let
		val m : int = 3
		val n : int = m*m
	in
		m*n
	end * m
///~注意m值的变化,如同入栈出栈
///~结果:r的值54

你可能感兴趣的:(sml,sml)