Created
August 10, 2014 02:13
-
-
Save bjhaid/497f950030c840efb619 to your computer and use it in GitHub Desktop.
An attempt to write ruby in a completely functional style, no classes or methods
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
require 'rspec' | |
module Anagram | |
FindAnagram = ->(word) do | |
words = File.readlines("/usr/share/dict/words") | |
dict = Anagram::Dictionary.(words) | |
dict[SplitSort.(word).join] | |
end | |
Dictionary = ->(words) do | |
words.reduce({}) do |hash, w| | |
sortedWord = SplitSort.(w.chomp).join | |
storedVal = hash[sortedWord] || [] | |
val = storedVal + [w.chomp] | |
hash.merge!(sortedWord => val) #hash.merge and hash.dup have been tried here but they both take forever proves trying to avoid mutation in ruby is almost impossible | |
end | |
end | |
DictionaryBlowsStack = ->(words, dict={}) do | |
if words.empty? | |
dict | |
else | |
word,remWords = words[0], words[1,words.size - 1] #This blows the stack after a few recursion demonstrating the fact that ruby does not have TCO(tail call optimization) | |
sortedWord = SplitSort.(word.chomp).join | |
dict[sortedWord] ||= [] | |
dict[sortedWord] << word.chomp | |
DictionaryBlowsStack.(remWords, dict) | |
end | |
end | |
SplitSort = ->(word) do | |
word.chars.sort | |
end | |
end | |
describe Anagram do | |
it "finds anagrams" do | |
Anagram::FindAnagram.("paste").should == ["paste", "septa", "spate"] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment