Skip to content

Instantly share code, notes, and snippets.

@arkadijs
Created December 15, 2012 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arkadijs/4299081 to your computer and use it in GitHub Desktop.
Save arkadijs/4299081 to your computer and use it in GitHub Desktop.
import Test.Hspec
import Data.List
anagrams :: [String] -> String -> [String]
anagrams lwords checkword = filter (wordsAreAnagrams checkword) lwords
wordsAreAnagrams :: String -> String -> Bool
wordsAreAnagrams a b = (a /= b) && (sort a == sort b)
allAnagrams :: [String] -> [[String]]
allAnagrams [] = []
allAnagrams (x:xs) = a:allAnagrams (xs \\ a)
where a = sort (x:anagrams xs x)
main :: IO ()
main = do
wordsAsString <- readFile "words.txt"
let lwords = lines wordsAsString
let anagramsWithWords = anagrams lwords
let tmpWords = ["enlist", "inlets", "listen", "silent", "blahblahblah"]
let tmpWords2 = ["inlets", "asdf", "fdas", "foo", "enlist"]
hspec $ do
describe "Anagrams" $ do
it "works for kinship" $ anagramsWithWords "kinship" `shouldBe` ["pinkish"]
it "works for pinkish" $ anagramsWithWords "pinkish" `shouldBe` ["kinship"]
it "works for enlist" $ anagramsWithWords "enlist" `shouldBe` ["inlets", "listen", "silent"]
it "works for boaster" $ anagramsWithWords "boaster" `shouldBe` ["boaters", "borates"]
it "works for boaster" $ anagramsWithWords "trouble" `shouldBe` []
it "should return [[String]]" $ allAnagrams tmpWords `shouldBe` [["enlist", "inlets", "listen", "silent"],["blahblahblah"]]
it "should return [[String]]" $ allAnagrams tmpWords2 `shouldBe` [["enlist", "inlets"], ["asdf", "fdas"], ["foo"]]
describe "wordsAreAnagrams" $ do
it "should return true" $ wordsAreAnagrams "listen" "silent" `shouldBe` True
it "should return true" $ wordsAreAnagrams "listen" "listen" `shouldBe` False
it "should return false" $ wordsAreAnagrams "knits" "pinkish" `shouldBe` False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment