OCaml入門

1はじめに

OCamlは関数型プログラミング言語です。

関連する入門資料は次のとおりです。

Rustと同様に、OCaml変数はデフォルトでは変更できません。次の例は、変数bbの例です。bの再定義。同じ変数値を変更する必要がある場合は、「mutable」キーワードを追加するか、参照を使用できます(キーワードは「ref」、参照値は演算子「:=」で変更されます)。参照値は次のとおりです。逆参照演算子「!」を使用してアクセスします。「ref」の根底にある本質は、可変フィールドの操作を容易にするために、可変フィールド+いくつかの再定義演算子を含むレコードです。

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