Skip to content

Instantly share code, notes, and snippets.

@tmcgilchrist
Created May 18, 2014 22:24
Show Gist options
  • Save tmcgilchrist/17183b0220965c14a1b1 to your computer and use it in GitHub Desktop.
Save tmcgilchrist/17183b0220965c14a1b1 to your computer and use it in GitHub Desktop.
Stack Data Type from Purely Function Data Structures.
module type Stack =
sig
type 'a t
val empty : 'a t
val isEmpty : 'a t -> bool
val cons : 'a -> 'a t -> 'a t
val head : 'a t -> 'a
val tail : 'a t -> 'a t
end
module MyStack : Stack = struct
type 'a t = 'a list
exception Empty
let empty = []
let isEmpty l =
match l with
| [] -> true
| _ -> false
let cons x l = x :: l
let head l =
match l with
| h :: _ -> h
| [] -> raise Empty
let tail l =
match l with
| _ :: r -> r
| [] -> raise Empty
end
(*
How do I create a usable Stack of say int from this definition?
I'm thinking something similar to module StringSet = Set.Make(String)
*)
@tmcgilchrist
Copy link
Author

You're right I don't need a functor at all. I was searching for how to bind 'a and didn't know how to specify the type.
Basically I can just go:

# let x = MyStack.cons 3 MyStack.empty;;
val x : int MyStack.t = <abstr>                                                 
# MyStack.head x;;
- : int = 3                                                                  

Thanks for that simple example, finding good OCaml examples is tricky.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment