Created
May 18, 2014 22:24
-
-
Save tmcgilchrist/17183b0220965c14a1b1 to your computer and use it in GitHub Desktop.
Stack Data Type from Purely Function Data Structures.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
*) |
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
I think, you don't need a functor here. This code should work just fine creating "stacks" of elements of any type.
Set.Make
is a functor because set elements require a function to compare them, so you have to provide a parameter module:Set.Make(Ord)
. Here,Ord
is a simple module that provides the functioncompare
.A simple example with functors: https://gist.github.com/a-nikolaev/b7aa74c20538e3350c15
It creates sorted lists, the module resembles Set.Make from the standard library.