OCaml简介

更新时间:2024-03-22 19:29:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

OCaml简介

2015-03-27

1 安装与配置

OCaml的安装项有

? ? ? ? ?

OCaml 相关lib

包管理工具OPAM 更好的交互式工具utop 更好的基础库扩展Core

1.1 安装OCaml以及相关lib Ubuntu

apt-get install ocaml ocaml-nox ocaml-native-compilers ocaml-doc ocaml-findlib oasis libpcre-ocaml-dev

Fedora

yum install ocaml ocaml-foo-devel ocaml-camlp4-devel ocaml-ocamldoc ocaml-findlib-devel ocaml-extlib-devel ocaml-calendar-devel

1.2 安装OPAM Ubuntu

apt-get install opam

Fedora需要先下载RPM包,然后使用rpm安装,类似于

rpm -ivh opam.rpm

安装完毕后需要使用普通用户进行配置

opam init

opam switch 4.01.0 eval `opam config env`

1.3 安装utop

opam install utop

1.4 安装与配置Core

opam install core

opam install async yojson core_extended core_bench cohttp async_graphics cryptokit menhir

然后编辑文件~/.ocamlinit,添加内容

#use \#thread;; #camlp4o;; #require \#require \#require “async”;;

2 OCaml语言简介

OCaml是一种函数式编程语言,并且兼有命令式、面向对象的特点,同时有很高的性能。OCaml已经在工业界有成熟的应用。 2.1 基本概念

一下简单针对注释、数值运算、基本类型(Tuple/List/Option/Record/Variant)、变量和函数进行了示例。注意每个语句最后的;;只是为了告诉交互式工具可以开始求值了,并不是必需的。

(* comments *)

(* integer operation *) 1 + 2;;

(* float number operation *) 1. +. 2.;;

(* tuple *) (1, “a”, 99.9);;

(* list *) [1; 2; 3;];;

(* option list *) [Some 1; None];;

(* record *)

type r = {a: int; b: string} {a = 1; b = “red”};

(* variant *)

type v = | Int of int * int | String of string [Int(1, 2); String(“center”)];;

(* variable binding *) let x = 1;;

(* function binding *) let add x y = x + y;;

(* recursive function and pattern matching *) let rec has_none x = match x with | [] -> false | None::_ -> true | _::rest -> has_none rest ;;

(* mutually recursive function *) let rec is_even x =

if x = 0 then true else is_odd (x - 1) and is_odd x =

if x = 0 then false else is_even (x - 1);;

2.2 代码组织

OCaml代码以模块的方式组织,一个模块由模块接口(.mli文件)和模块实现(.ml)文件组成,且.mli和.ml文件的命名需要完全一致,且全部由小写字母和下划线组成。这样建立的模块对应的模块名称与文件名相同,但是首字母需要大写。 下面是一个简单示例,用来在一个字符串列表中判断一个字符串是否存在

(* File find_str.mli *) type t

val find : string list -> string -> bool

(* File find_str.ml *) open Core.Std type t = string list let find strlist str =

match List.find ~f:(fun x -> x = str) strlist with | None -> false | Some _ -> true

实际上,在上边的.ml文件中,已经使用了其他的模块。如果我们需要在另一个文件中引用模块Find_str,可以使用

open Find_str find [“a”; “b”] “a”

2.3 工程管理 //todo

2.4 多进程管理 /todo

本文来源:https://www.bwwdw.com/article/gg88.html

Top