Created
July 20, 2018 09:04
-
-
Save busypeoples/1bcfd052f0c4e493743d43f41bc1821e to your computer and use it in GitHub Desktop.
Data Structures in ReasonML: #2 Stack
This file contains hidden or 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
/* Stack */ | |
/* LIFO: Last In First Out*/ | |
exception Empty; | |
module type Stack = { | |
type stack('a) = list('a); | |
let create: unit => stack('a); | |
let push: ('a, stack('a)) => stack('a); | |
let pop: stack('a) => stack('a); | |
let peak: stack('a) => 'a; | |
let isEmpty: stack('a) => bool; | |
let length: stack('a) => int; | |
let map: ('a => 'b, stack('a)) => stack('b); | |
let iter: ('a => unit, stack('a)) => unit; | |
}; | |
module Stack: Stack = { | |
/* We can implement the stack with a list*/ | |
type stack('a) = list('a); | |
/* Initialize an empty stack */ | |
let create = () => []; | |
/* A new stack with the item added at the top of stack */ | |
let push = (value, stack) => [value, ...stack]; | |
/* A new stack with an item removed from the top of stack */ | |
let pop = stack => | |
switch (stack) { | |
| [_head, ...rest] => rest | |
| [] => raise(Empty) | |
}; | |
/* Access the item at the top of the stack */ | |
let peak = stack => | |
switch (stack) { | |
| [head, ..._rest] => head | |
| [] => raise(Empty) | |
}; | |
let length = stack => List.length(stack); | |
let isEmpty = stack => | |
switch (stack) { | |
| [] => true | |
| _ => false | |
}; | |
/* Return a new stack by applying the | |
mapping function on every item in the stack */ | |
let map = (fn, stack) => List.map(fn, stack); | |
/* Applies the provided function on every item in the stack */ | |
let iter = (fn, stack) => List.iter(fn, stack); | |
}; | |
let run = () => { | |
let s = Stack.create(); | |
let s = Stack.push(1, s); | |
let s = Stack.push(2, s); | |
let s = Stack.push(4, s); | |
Js.log("Log values"); | |
Js.log(Stack.iter(a => Js.log(a), s)); | |
Js.log("peak: "); | |
Js.log(Stack.peak(s)); | |
let s = Stack.push(20, s); | |
Js.log("peak: "); | |
Js.log(Stack.peak(s)); | |
Js.log("pop"); | |
let s = Stack.pop(s); | |
Js.log("map: a => a * 2: "); | |
let s = Stack.map(a => a * 2, s); | |
Js.log("Log values"); | |
Js.log(Stack.iter(a => Js.log(a), s)); | |
Js.log("peak: "); | |
Js.log(Stack.peak(s)); | |
Js.log("isEmpty? "); | |
Js.log(Stack.isEmpty(s)); | |
Js.log("length: "); | |
Js.log(Stack.length(s)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment