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

The OCaml Language Cheatsheets

作者头像
绿巨人
发布于 2020-04-09 03:52:08
发布于 2020-04-09 03:52:08
54500
代码可运行
举报
文章被收录于专栏:绿巨人专栏绿巨人专栏
运行总次数:0
代码可运行

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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
open Unix               (* global open *)
let open Unix in expr   (* local open *)
Unix.(expr)             (* local open *)

Functions

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
while cond do ... done;
for var = min_value to max_value do ... done;
for var = max_value downto min_value do ... done;

Exceptions

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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 删除。

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Scala类型推导Scala类型推导
根据Picrce的说法:“类型系统是一个可以根据代码段计算出来的值对它们进行分类,然后通过语法的手段来自动检测程序错误的系统。”
一个会写诗的程序员
2018/08/20
2.6K0
this类型_TypeScript笔记11
返回类型是this,表示所属类或接口的子类型(称之为有界多态性(F-bounded polymorphism)),例如:
ayqy贾杰
2019/06/12
7480
TVM 学习指南(个人版)
最近粗略的看完了天奇大佬的MLC课程(顺便修了一些语法和拼写错误,也算是做了微弱的贡献hh),对TVM的近期发展有了一些新的认识。之前天奇大佬在《新一代深度学习编译技术变革和展望》一文中(链接:https://zhuanlan.zhihu.com/p/446935289)讲解了TVM Unify也即统一多层抽象的概念。这里的统一多层抽象具体包括AutoTensorization用来解决硬件指令声明和张量程序对接,TVM FFI(PackedFunc)机制使得我们可以灵活地引入任意的算子库和运行库函数并且在各个编译模块和自定义模块里面相互调用。TensorIR负责张量级别程序和硬件张量指令的整合。Relax (Relax Next) 引入relay的进一步迭代,直接引入first class symbolic shape的支持 (摘抄自《新一代深度学习编译技术变革和展望》一文)。然后这些抽象可以相互交互和联合优化来构造深度学习模型对应的最终部署形式。我个人感觉TVM Unify类似于MLIR的Dialect,但是这几个抽象的直接交互能力相比于MLIR的逐级lower我感觉是更直观方便的,毕竟是Python First(这个只是我最近看MLC课程的一个感觉)。对这部分内容感兴趣的读者请查看天奇大佬的TVM Unify介绍原文以及MLC课程。
BBuf
2022/09/28
3.9K0
TVM 学习指南(个人版)
再再肝3天,整理了70个Python面向对象编程案例
Python 作为一门面向对象编程语言,常用的面向对象知识怎么能不清楚呢,今天就来分享一波
周萝卜
2021/11/24
7440
「SF-LC」6 Logic
The equality operator = is also a function that returns a Prop. (property: equality)
零式的天空
2022/03/14
6090
.NET DLR 上的IronScheme 语言互操作&&IronScheme控制台输入中文的问题
前言 一直以来对Lisp语言怀有很崇敬的心里,《黑客与画家》对Lisp更是推崇备至,虽然看了不少有关Lisp的介绍但都没有机会去写段程序试试,就像我对C++一样,多少有点敬畏。这个周末花了不少时间来研究Lisp。 Lisp是古老的函数式语言,跟C,C++等命令式语言完全不一样的编程风格,但Lisp的方言很多,最后Lisp标准委员制定了Common Lisp,但内容很长,有1000多页,因此功能比较强大;而Lisp的另外一个主要分支就是Scheme,它的标准内容只有不到100页,所以非常简单,适合学术研究和大
用户1177503
2018/02/27
1.1K0
.NET DLR 上的IronScheme 语言互操作&&IronScheme控制台输入中文的问题
Spark2.x学习笔记:2、Scala简单例子
2、 Scala简单例子 参考教程:https://yq.aliyun.com/topic/69 2.1 交互式编程 spark-shell是Spark交互式运行模式,提供了交互式编程,边敲代码边执
程裕强
2018/01/02
3.2K0
SqlAlchemy 2.0 中文文档(三十一)
1.4 版本更改:绝大部分声明式扩展现在已整合到 SQLAlchemy ORM 中,并可从 sqlalchemy.orm 命名空间导入。请参阅声明式映射的文档以获取新文档。有关更改的概述,请参阅声明式现已与 ORM 整合,并带有新功能。
ApacheCN_飞龙
2024/06/26
7340
从TypeScript到ArkTS迁移的保姆级指导
本文通过提供简洁的约束指导如何将标准的TypeScript代码重构为ArkTS代码。尽管ArkTS是基于TypeScript设计的,但出于性能考虑,一些TypeScript的特性被限制了。因此,在ArkTS中,所有的TypeScript特性被分成三类。
小帅聊鸿蒙
2024/07/07
9710
从TypeScript到ArkTS迁移的保姆级指导
C++可调用Callable类型的总结
自从在使用 std::thread 构造函数过程中遇到了 Callable 类型的概念以来用到了很多关于它的使用. 因此本文把使用/调查结果总结出来. 包括 Callable 的基础概念, 典型的 Callable 类型介绍. 例如函数对象(狭义), 函数指针, lambda 匿名函数, 函数适配器, std::function 仿函数等.
高性能架构探索
2023/09/05
3510
C++可调用Callable类型的总结
SWIG 官方文档第四部分 - 机翻中文人肉修正
包装 C 库时出现的一个常见问题是保持可靠性和检查错误。事实是,许多 C 程序因不提供错误检查而臭名昭著。不仅如此,当您将应用程序的内部结构公开为库时,通常可以通过提供错误的输入或以非预期的方式使用它而使其崩溃。
韩伟
2021/09/03
5.6K0
SWIG 官方文档第二部分 - 机翻中文人肉修正
本章简要概述了 C++11 标准的 SWIG 实现。SWIG 的这一部分仍在进行中。
韩伟
2021/09/03
2.5K0
C++ 中文周刊 第114期
确实,学生很需要这些,不然都得从头学,不知道我的读者学生多不多,如果没学,这里补课 https://missing-semester-cn.github.io/
王很水
2023/05/20
5640
上手指南 | Dart,随用随查
dynamic:该类型具有所有可能的属性和方法,一个变量被 dynamic 修饰,相当于告诉系统,我知道这个类型到底是什么。使用后再编译时不会推断数据的类型,但是运行时会推断。
345
2022/02/11
1.9K0
上手指南 | Dart,随用随查
PyTorch 源码解读之即时编译篇
来源丨https://zhuanlan.zhihu.com/p/361101354
BBuf
2021/07/01
1.3K0
PyTorch 源码解读之即时编译篇
Scala Macros - 元编程 Metaprogramming with Def Macros
    Scala Macros对scala函数库编程人员来说是一项不可或缺的编程工具,可以通过它来解决一些用普通编程或者类层次编程(type level programming)都无法解决的问题,这
用户1150956
2018/01/05
3.2K0
Kotlin 编码规约
如需根据本风格指南配置 IntelliJ 格式化程序,请安装 Kotlin 插件1.2.20 或更高版本,转到“Settings | Editor | Code Style | Kotlin”,点击右上角的“Set from...”链接,并从菜单中选择“Predefined style / Kotlin style guide”。
一个会写诗的程序员
2019/07/26
3.3K0
Kotlin 编码规约
php pwn学习入门二 (格式化字符串漏洞)
本文是学习php二进制漏洞利用的第二篇文章,格式化字符串漏洞是CTF比赛中比较常见的漏洞,本文主要介绍一下64位下php中的格式化字符串漏洞的利用思路。
用户1879329
2023/02/27
4870
php pwn学习入门二 (格式化字符串漏洞)
「SF-LC」15 Extraction
如果不做任何处理的话…生成的 ml 里的 nat 则都会是 Church Numeral…
零式的天空
2022/03/14
5400
《dive into python3》 笔记摘录
s1mba
2017/12/28
1.3K0
《dive into python3》 笔记摘录
相关推荐
Scala类型推导Scala类型推导
更多 >
加入讨论
的问答专区 >
1先锋会员擅长2个领域
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档