sml基本语法(一)

注释

(* *)(不是单行注释//块注释/* */

运算

  1. 一元操作符没有+-,表示负数应该使用~,eg:~6表示-6
  2. 整数除法div(除术算法),实数除法/,取余(模)mod(不是%
  3. 函数运用比中缀运算符优先级更高
    函数的形参列表可以不用括号"()"括住,如下
area (1.0);
area 1.0 //二者等价

PS: area a + b 等价于 (area a) + b不等价于 area (a + b)

类型

有哪些类型?
ML中的内置类型有int,real,char,stringbool,见下表(不全)

类型 操作数
real 3.14, 2.17, 0.1E6, . . . +, -, *, /, =, <, . . .
char #“a”, #“b”, . . . ord,chr,=, <, . . .
string “abc”, “1234”, . . . ˆ, size, =, <, . . .
bool true, false if exp then exp1 else exp2

详见:Basic Library
类型断言(typing assertion)
exp : typexp表达式,typ类型)

  1. 表达式的类型:(由于一个表达式的类型一定确定,或者说由type checker确定)我们说类型声明是有效的当且仅当exp的类型确实是typ,比如下面的例子
    3 : i n t 3 + 4 : i n t 4 d i v 3 : i n t 4 m o d 3 : i n t 3 : int\\ 3 + 4 : int\\ 4 div 3 : int\\ 4 mod 3 : int 3:int3+4:int4div3:int4mod3:int
    否则,interactive system 会给如下报错
///~input
- 3 + 4 : real;
///~output
stdIn:1.2-1.14 Error: expression does not match constraint [overload conflict]
  expression: [+ ty]
  constraint: real
  in expression:
    3 + 4: real

表达式类型断言的语句(expressions of typing assertion)没有实际用处,但这说明ML语言中存在严格的类型约束

  1. 类型约束
    (1)

ML可以根据表达式里面用到的函数和常量的类型推导出大多数表达式的类型。不过某些内置的函数是被重载(overloaded )了的,它们不止有一个含义。例如,对于整敬和实数中都有定义.重载函数的类型必须由上下文来确定,偶尔必须显式地指出。

///~input
- fun square x = x*x;
///~output
Error-Unable to resolve overloading tor *

应改为
fun square (x : real) = x*x;

--《ML程序设计教程》

实际测试(可能是smlnj版本不同,不过引用中的例子主要说明存在严格的类型检测)

- fun square x = x*x;
val square = fn : int -> int

这里也说明参数当类型不确定时,默认定为int
(2)

加法操作+realint进行重载。在涉及加法的表达式中,type checker尝试识别你的参数类型. 如果参数是两个int类型数,,那么定点数加法(fixed point addition)被使用;如果参数是两个real类型数,那么浮点数加法(floating addition)将被使用;否则将会收到报错。

例如
3 + 3.14 3+3.14 3+3.14 is rejected as ill-formed
应该改为real(3) + 3.14

  1. 如何判断表达式的类型?
    例如 ( 3 + 4 ) (3+4) (3+4) d i v div div 5 : i n t 5 : int 5:int
    (1) 5是int,由公理决定(公认的,或者说是 i n t int int本身的定义)
    (2) 操作符 d i v div div 两端的操作数的类型均为int,所以表达式 ( 3 + 4 ) (3+4) (3+4) d i v div div 5 5 5 i n t int int
    (表达式 3 + 4 3 + 4 3+4 的类型为 i n t int int,理由同(2))
    (3) 表达式的值由表达式的类型决定,该例中结果为val it = 0 : int

参考文献
[1]Programming in Standard ML (DRAFT: VERSION 1.2OF 11.02.11.)By Robert Harper, Carnegie Mellon University, Spring Semester, 2011
[2]ML程序设计教程

你可能感兴趣的:(sml)