Last active
March 5, 2016 13:44
-
-
Save Kuchitama/8a2ce04cdf7edbe22e06 to your computer and use it in GitHub Desktop.
#rubykansai 第71回のハンズオンでやった Stackを実装する課題をなんとなくイミュータブルに実装してみた
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
ruby "2.3.0" | |
gem "test-unit" |
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
class MyStack | |
def self.empty | |
MyStack.new(nil) | |
end | |
def initialize head, next_stack = nil | |
if head == nil | |
@elem = head | |
@next = nil | |
else | |
raise StandardError.new if (not next_stack.is_a?(MyStack)) && next_stack != nil | |
@elem = head | |
@next = next_stack | |
end | |
end | |
def empty? | |
@elem == nil | |
end | |
def size | |
if empty? then | |
0 | |
else | |
1 + @next.size | |
end | |
end | |
def push val | |
MyStack.new(val, self) | |
end | |
def pop | |
raise EmptyStackError.new if @elem == nil | |
@next | |
end | |
def pop2 | |
{head: @elem, tail: pop} | |
end | |
class EmptyStackError < StandardError | |
end | |
end |
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
require 'test/unit' | |
require_relative 'mystack' | |
class TestMyStack < Test::Unit::TestCase | |
def setup | |
@empty = MyStack.empty | |
@empty.freeze | |
end | |
def test_new | |
assert_raise(StandardError) do | |
MyStack.new(1, 2) | |
end | |
MyStack.new(1) | |
end | |
def test_epmty_by_empty_mystack | |
assert_equal @empty.empty?, true | |
end | |
def test_epmty_by_non_mystack | |
assert_equal MyStack.new(3).empty?, false | |
end | |
def test_empty_by_nonempty_mystack | |
stack = MyStack.new(3) | |
assert stack.empty? == false, "non epmpty stack must return false" | |
end | |
def test_size_by_mystack | |
assert_equal @empty.size, 0 | |
oneStack = @empty.push(3) | |
assert_equal oneStack.size, 1 | |
twoStack = oneStack.push(5) | |
assert_equal twoStack.size, 2 | |
end | |
def test_pop_by_empty_mystack | |
assert_raise(MyStack::EmptyStackError) do | |
@empty.pop | |
end | |
end | |
def test_pop_by_mystack | |
stack = @empty.push(3).push(5) | |
assert_equal stack.pop2[:head], 5 | |
assert_equal stack.pop2[:tail].pop2[:head], 3 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment