Skip to content

Instantly share code, notes, and snippets.

@igor-shevchenko igor-shevchenko/anagram.hs
Last active Dec 17, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.