Ocaml 入门整理2

来源:互联网 发布:淘宝店名大全女装 编辑:程序博客网 时间:2024/04/30 09:29

Ocaml Standard Library

了解Module

  • Structure = implementation of module
  • signture = interface of module

signture 有点类似Java 里面的Interface

举个例子

module type STACK = 
sig
   type 'a t         
   exception Empty
   val empty : 'a t
   val push : 'a -> 'a t ->'a t
   val pop : 'a t -> 'a * 'a t
  end;;

上面的代码是说 Stack 这个Module 具有两个field:type t 和 exception Empty
然后就是3个function: empty, push, pop /

那么STACK 到底是怎么具体实现的呢

module MyStack =struct
    type t = int list
    exception Empty
    let empty = []
    let push x t = x :: t
    let pop t =
        match t with
        [] -> raise Empty
            |h::t -> (h, t)
            let first t =
                match t with
                [] -> raise Empty
                |h::t -> h
    end

原创粉丝点击