前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >The OCaml Language Cheatsheets

The OCaml Language Cheatsheets

作者头像
绿巨人
发布2020-04-09 11:52:08
5020
发布2020-04-09 11:52:08
举报
文章被收录于专栏:绿巨人专栏

The OCaml Language Cheatsheets

OCaml v.4.08.1

Syntax

Implementations are in .ml files, interfaces are in .mli files. Comments can be nested, between delimiters (*...*) Integers: 123, 1_000, 0x4533, 0o773, 0b1010101 Chars: 'a', '\255', '\xFF', '\n' Floats: 0.1, -1.234e-34

Data Types

代码语言:javascript
复制
unit:             (* void, takes only one value: () *)
int:              (* integer of either 31 or 63 bits, like 42 *)
int32:            (* 32 bits Integer, like 42l *)
int64:            (* 64 bits Integer, like 42L *)
float:            (* double precision float, like 1.0 *)
bool:             (* boolean, takes two values: true or false *)
char:             (* simple ASCII characters, like 'A' *)
string:           (* strings, like "Hello" or foo|Hello|foo *)
bytes:            (* mutable string of chars *)
'a list :         (* lists, like head :: tail or [1;2;3] *)
'a array:         (* arrays, like [|1;2;3|] *)
t1 * ... * tn:    (* tuples, like (1, "foo", 'b') *)

Constructed Types

代码语言:javascript
复制
type record =               (* new record type *)
{ field1 : bool;            (* immutable field *)
  mutable field2 : int; }   (* mutable field *)

type enum =                 (* new variant type *)
  | Constant                (* Constant constructor *)
  | Param of string         (* Constructor with arg*)
  | Pair of string * int    (* Constructor with args *)
  | Gadt : int -> enum      (* GADT constructor *)
  | Inlined of { x : int }  (* Inline record *)

Constructed Values

代码语言:javascript
复制
let r = { field1 = true; field2 = 3; }
let r' = { r with field1 = false }
r.field2 <- r.field2 + 1;
let c = Constant
let c = Param "foo"
let c = Pair ("bar",3)
let c = Gadt 0
let c = Inlined { x = 3 }

References, Strings and Arrays

代码语言:javascript
复制
let x = ref 3   (* integer reference (mutable) *)
x := 4          (* reference assignation *)
print_int !x;   (* reference access *)
s.[0]           (* string char access *)
t.(0)           (* array element access *)
t.(0) <- x      (* array element modification *)

Imports - Namespaces

代码语言:javascript
复制
open Unix               (* global open *)
let open Unix in expr   (* local open *)
Unix.(expr)             (* local open *)

Functions

代码语言:javascript
复制
let f x = expr                (* function with one arg *)
let rec f x = expr            (* recursive function, apply: f x *)
let f x y = expr              (* with two args, apply: f x y *)
let f (x,y) = expr            (* with a pair as arg, apply: f (x,y) *)
List.iter (fun x -> expr)     (* anonymous function *)
let f = function None -> act  (* function definition *)
      | Some x -> act         (* function definition [by cases] *)
                              (* apply: f (Some x) *)
let f ~str ~len = expr        (* with labeled args *)
                              (* apply: f ~str:s ~len:10 *)
                              (* apply: (for ~str:str):  f ~str ~len *)
let f ?len ~str = expr        (* with optional arg (option) *)
let f ?(len=0) ~str = expr    (* optional arg default *)
                              (* apply (with omitted arg): f ~str:s *)
                              (* apply (with commuting): f ~str:s ~len:12 *)
                              (* apply (len: int option): f ?len ~str:s *)
                              (* apply (explicitly omitted): f ?len:None ~str:s *)
let f (x : int) = expr        (* arg has constrainted type *)
let f : 'a 'b. 'a*'b -> 'a    (* function with constrainted *)
      = fun (x,y) -> x        (* polymorphic type *)

Modules

代码语言:javascript
复制
module M = struct .. end            (* module definition *)
module M: sig .. end= struct .. end (* module and signature *)
module M = Unix                     (* module renaming *)
include M                           (* include items from *)
module type Sg = sig .. end         (* signature definition *)
module type Sg = module type of M   (* signature of module *)
let module M = struct .. end in ..  (* local module *)
let m = (module M : Sg)             (* to 1st-class module *)
module M = (val m : Sg)             (* from 1st-class module *)
module Make(S: Sg) = struct .. end  (* functor *)
module M = Make(M')                 (* functor application *)

Module type items: val, external, type, exception, module, open, include, class

Pattern-matching

代码语言:javascript
复制
match expr with
  | pattern -> action
  | pattern when guard -> action    (* conditional case *)
  | _ -> action                     (* default case *)
Patterns:
  | Pair (x,y) ->                   (* variant pattern *)
  | { field = 3; _ } ->             (* record pattern *)
  | head :: tail ->                 (* list pattern *)
  | [1;2;x] ->                      (* list pattern *)
  | (Some x) as y ->                (* with extra binding *)
  | (1,x) | (x,0) ->                (* or-pattern *)
  | exception exn ->                (* try&match *)

Conditionals

Do NOT use on closures

代码语言:javascript
复制
x = y           (* (Structural) Polymorphic Equality *)
x == y          (* (Physical) Polymorphic Inequality *)
x <> y          (* (Structural) Polymorphic Equality *)
x != y          (* (Physical) Polymorphic Inequality *)
compare x y     (* negative, when x < y *)
compare x y     (* 0, when x = y *)
compare x y     (* positive, when x > y *)

Other Polymorphic Comparisons: >, >=, <, <=

Loops

代码语言:javascript
复制
while cond do ... done;
for var = min_value to max_value do ... done;
for var = max_value downto min_value do ... done;

Exceptions

代码语言:javascript
复制
exception MyExn                 (* new exception *)
exception MyExn of t * t'       (* same with arguments  *)
exception MyFail = Failure      (* rename exception with args *)
raise MyExn                     (* raise an exception *)
raise (MyExn (args))            (* raise with args *)
try expr                        (* catch MyExn *)
with MyExn -> ...               (* if raised in expr *)

Objects and Classes

代码语言:javascript
复制
class virtual foo x =           (* virtual class with arg *)
  let y = x+2 in                (* init before object creation *)
  object (self: 'a)             (* object with self reference *)
  val mutable variable = x      (* mutable instance variable *)
  method get = variable         (* accessor *)
  method set z =
    variable <- z+y             (* mutator *)
  method virtual copy : 'a      (* virtual method *)
  initializer                   (* init after object creation *)
    self#set (self#get+1)
end

class bar =                     (* non-virtual class *)
  let var = 42 in               (* class variable *)
  fun z -> object               (* constructor argument *)
  inherit foo z as super        (* inheritance and ancestor reference *)
  method! set y =               (* method explicitly overridden *)
    super#set (y+4)             (* access to ancestor *)
  method copy = {< x = 5 >}     (* copy with change *)
end
let obj = new bar 3             (* new object *)
obj#set 4; obj#get              (* method invocation *)
let obj = object .. end         (* immediate object *)

Polymorphic variants

代码语言:javascript
复制
type t = [ `A | `B of int ]       (* closed variant *)
type u = [ `A | `C of float ]
type v = [ t | u | ]              (* union of variants *)
let f : [< t ] -> int = function  (* argument must be a subtype of t *)
  | `A -> 0 | `B n -> n
let f : [> t ] -> int = function  (* t is subtype of the argument *)
  |`A -> 0 | `B n -> n | _ -> 1

Reference

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-04-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • The OCaml Language Cheatsheets
    • Syntax
      • Data Types
        • Constructed Types
          • Constructed Values
            • References, Strings and Arrays
              • Imports - Namespaces
                • Functions
                  • Modules
                    • Pattern-matching
                      • Conditionals
                        • Loops
                          • Exceptions
                            • Objects and Classes
                              • Polymorphic variants
                                • Reference
                                领券
                                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档