thyecust/thyecust.github.io

OCaml 上手

Opened this issue · 0 comments

资源

我在 Ubuntu WSL 上运行。

简单介绍

Caml(Categorical Abstract Machine Language)是 INRIA 在 1987 年创造的语言,1990 年发展为 Caml Light,1995 年发展为 OCaml。

OCaml 拓展了 Caml 语言,在这些方面

  • 一个成熟的 OO 层
  • 强大的模块系统
  • 一个 sound 而且 polymorphic 的类型系统

OCaml 是一门函数式编程语言。

关于函数式编程

函数式编程的特点包括

  • 不可变的数据结构
  • 递归是最重要的控制结构
  • 经常使用高阶函数

与之相对的是命令式编程

  • 可变的数据结构
  • 循环比递归重要
  • 一阶函数比高阶函数重要

Top level

OCaml 既有一个编译器,可以生成可运行的二进制文件,也有一个交互的 top level,可以用于实验或者小程序。

# "Hello World";;
- : string = "Hello World"
# 16+18;;
- : int = 34
# 2*8+3*6;;
- : int = 34

三元表达式的两个分支应该有相同的类型

# if 1<2 then 1 else 2;;
- : int = 1
# if 1<2 then 1 else 1.1;;
Error: This expression has type float but an expression was expected of type
         int

基本类型

char

# 'x';;
- : char = 'x'
# '\120';;
- : char = 'x'

string

# "hello world";;
- : string = "hello world"
# "hello world".[2];;
- : char = 'l'

bool

# true;;
- : bool = true
# true && false;;
- : bool = false
# true || false;;
- : bool = true

OCaml 是一门强类型语言,在 OCaml 里没有 casting。