A fun joke based on Evolution of a Haskell Programmer.
require "minitest/autorun"
def factorial n
raise ArgumentError, "Out of Range" if n.negative?
if n.zero? then
1
else
result = factorial n - 1
n * result
end
end
class TestFactorial < Minitest::Test
def test_zero
result = factorial 0
assert_equal result, 1
end
def test_five
result = factorial 5
assert_equal result, 120
end
end
require 'test/unit'
def fac(n)
if n.negative? then raise ArgumentError, "Out of range" end
if n.zero? then return 1 end
total = n
while (n -= 1) > 0
total *= n
end
total
end
class FacTest < Test::Unit::TestCase
def test_failure
assert_raises { fac(-1) }
end
def test_zero
assert(fac(0) == 1)
end
def test_five
assert(fac(5) == 120)
end
end
require "rspec/autorun"
def factorial(n) = n.zero? ? 1 : n * factorial(n - 1)
RSpec.describe "#factorial" do
let(:result) { factorial(n) }
context "When given 0" do
let(:n) { 0 }
it "should equal 1" do
expect(result).to eq(0)
end
end
context "When given 5" do
let(:n) { 5 }
it "should equal 120" do
expect(result).to eq(120)
end
end
# TODO: go/jira/FACT-1234 - Handle negatives
xcontext "When given a negative number" do
end
end
($_=->_{@_=$$/$$;_<=@_?@_:_*$_[_-@_]})[5]
class Numeric
def fibonacci
raise ArgumentError, "Out of bounds" if negative?
(1..self).reduce(:*)
end
end
5.fibonacci
require 'dry/monads'
extend Dry::Monads[:result]
def fibonacci(n)
return Failure("Out of bounds") if n.negative?
Success((1..n).reduce(:*))
end
gem 'memo_wise'
prepend MemoWise
memo_wise def fibonacci(n)
raise ArgumentError, "Out of bounds" if n.negative?
(1..n).reduce(:*)
end
As I feel deeply seen by the San Franciso entry (using RSpec), I also wanted to fill in the missing characters in the code golf approach.
It needs an
n *
i.e. It should read:As first written, it will always return 1 for non-negative numbers.
Both the original and the fixed version will cause a stack overflow for any negative number (since we don't believe in ArgumentErrors, I guess!)