Skip to content

Instantly share code, notes, and snippets.

@igor-shevchenko
Last active December 17, 2015 02:19
Show Gist options
  • Save igor-shevchenko/5534820 to your computer and use it in GitHub Desktop.
Save igor-shevchenko/5534820 to your computer and use it in GitHub Desktop.
import Data.List (deleteFirstsBy, null)
import System.IO.UTF8 (readFile)
anagrams :: [Char] -> [String] -> [String]
anagrams [] _ = [""]
anagrams _ [] = []
anagrams letters dictionary =
let currentWord = head dictionary
remainingLetters = removeWord letters currentWord
newDictionary = filterDictionary remainingLetters dictionary
anagramsOfRemainingLetters = anagrams remainingLetters newDictionary
anagramsWithoutCurrentWord = anagrams letters $ tail dictionary
in (prependWord currentWord anagramsOfRemainingLetters) ++ anagramsWithoutCurrentWord
removeWord :: [Char] -> String -> [Char]
removeWord = deleteFirstsBy (==)
prependWord :: String -> [String] -> [String]
prependWord word = map (\x -> word ++ " " ++ x)
filterDictionary :: [Char] -> [String] -> [String]
filterDictionary letters = filter (\x -> null $ deleteFirstsBy (==) x letters)
main = do
dictionary <- fmap lines (System.IO.UTF8.readFile "dict.txt")
letters <- fmap (concat . words) getLine
putStr $ unlines $ anagrams letters $ filterDictionary letters dictionary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment