OCaml入门

1. 引言

OCaml为函数式编程语言。

相关入门资料有:

OCaml变量与Rust类似,默认是not mutable的。如下例,是对变量 b b b的重定义。若需对同一变量值进行修改,可加“mutable”关键字,或使用引用(关键字为“ref”,引用值修改用操作符":="),访问引用值 使用 解引用操作符"!"。而“ref”的底层本质就是a record with a mutable filed + some re-define operators to facilitate manipulation of the mutable field。

utop # let a =
    let b = 5 in 
    let b = 5 + b in 
    b;;
val a : int = 10

utop # type bus = { mutable passengers : int };;
type bus = {
    
     mutable passengers : int; }

utop # let shuttle = { passengers = 0 };;
val shuttle : bus = {
    
    passengers = 0}

utop # shuttle.passengers <- 3;;
- : unit = ()

utop # shuttle;;
- : bus = {
    
    passengers = 3}

utop # let counter = ref 0;;
val counter : int ref = {
    
    contents = 0}

utop # counter := 3;;
- : unit = ()

utop # counter;;
- : int ref = {
    
    contents = 3}

utop # !counter + 4;;
- : int = 7

utop # type 'a ref = { mutable contents : 'a }
let (:=) r v = r.contents <- v
let (!) r = r.contents;;
type 'a ref = { mutable contents : 'a; }
val ( := ) : 'a ref -> 'a -> unit = <fun>
val ( ! ) : 'a ref -> 'a = <fun>

猜你喜欢

转载自blog.csdn.net/mutourend/article/details/123404890