Created
July 28, 2013 07:09
-
-
Save weidagang/6097782 to your computer and use it in GitHub Desktop.
Functional 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
| #!/usr/bin/env node | |
| function make_stack() { | |
| return null | |
| } | |
| function push(stack, x) { | |
| return { | |
| top : function() { return x }, | |
| pop : function() { return stack } | |
| } | |
| } | |
| function top(stack) { | |
| return stack.top() | |
| } | |
| function pop(stack) { | |
| return stack.pop() | |
| } | |
| // Test case | |
| var stack = make_stack() | |
| stack = push(stack, 1) | |
| stack = push(stack, 2) | |
| stack = push(stack, 3) | |
| console.log(top(stack)) // 3 | |
| stack = pop(stack) | |
| console.log(top(stack)) // 2 | |
| stack = push(stack, 4) | |
| console.log(top(stack)) // 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment