这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战」
Mutability (可变性)
命令式语言,如C、Java,在程序执行的过程中涉及到可变状态。
可变的好处在于程序很容易理解,机器做完这个 然后做这个。。。
但是可变性的现实遇到的问题是,尽管机器很擅长复杂的状态操作,但是人类不擅长。在数学上,如果,你可以用来替换任何地方的。在命令式语言中,你不能直接替换,因为在时间计算机的与时间 时候不一样。
OCaml 是第一个状态不变的语言,和所有的PF一样。
OCaml 基本语法
类型和值
- 在控制台中使用
;;结束一个表达式
# 42;;
- : int = 42
# let x = 42;;
val x : int = 42
函数
- 函数在Ocaml中可以定义成:
# let increment x = x + 1;;
val increment : int -> int = <fun>
# increment 0;;
- : int = 1
# increment 21;;
- : int = 22
# increment(increment 5) ;;
- : int = 7
其中,
increment是函数值绑定的标识符int -> int为值的类型- 可以把这个函数看成一个类型。toplevel 是不会将其打印出来,因为此时该段代码还没有被编译。相反toplevel会打印
<fun>,这仅仅是一个占位符,暗示这是一个无法打印的函数值。注意的是,<fun>不是值。 - 在 Ocaml中我们不会用“调用call函数”而是使用“应用apply函数”
在toplevel中加载代码
# #use "mycode.ml";;
val inc : int -> int = <fun>
# inc 3;;
- : int = 4
#
表达式
reference page : ocaml.org/manual/expr…
Assertions
The expression assert e evaluates e. If the result is true, nothing more happens, and the entire expression evaluates to a special value called unit. The unit value is written () and its type is unit. But if the result is false, an exception is raised.
操作符
-
OCaml 不支持操作符重载
- 两个Int 类型相加使用
+; 如果加一个浮点数 则使用+.
- 两个Int 类型相加使用
-
Operators
=and<>examine structural equality whereas==and!=examine physical equality