Skip to content

Instantly share code, notes, and snippets.

@bjhaid
Created August 10, 2014 02:13
Show Gist options
  • Save bjhaid/497f950030c840efb619 to your computer and use it in GitHub Desktop.
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
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