0
votes

my assignment is to make a word solver in Haskell. The idea is that you are given a few random letters. You can type these random letters in Haskell and it returns a list of words that the letter can form. For learning more about this, i've used Haskell compare all list items however i'm now stuck at the last part:
I have a function which reads in a file and stores every word in a line:

getList :: FilePath -> IO [String]
getList path= do contents<- readFile "wordlist.txt"
                 return(lines contents)

Then I also have another function called randomTiles:

randomTiles :: [Char] -> [Char] -> Bool
randomTiles word letters = all (\c  -> LettersinWord' c word letters) word

This function basically looks at the input of random letters you have given and shows the user if a word can be formed with them, if yes it returns true else false.

Now I have to make a function which loads the getList into the randomTiles so that the given random letters can be compared with the words of the list. If randomTiles returns true, it has to print the word that can be formed. However I really have no idea how to go about this since i'm new to Haskell and i'm not even sure its possible. I have tried it in this way but i'm sure its not the way to do it:

solver:: [Char]->[String]
solver a = test1
    where 
    randomTiles a b = getList a 
    test1= if randomTiles = true then print

To make sure, the code is supposed to work like this; my given letters are "lohel" output: hello hell hole

2

2 Answers

1
votes

I would start by making a function that tests the randomTiles against all the words in a given dictionary:

allMatches :: [Char] -> [String] -> [String]
allMatches randomLetters words =
    filter (\word -> randomTiles word randomLetters) words

I think of the 'solver' as loading the word dictionary and returning a new function that will print all the words that can be formed from a set of random letters. There are a couple variations of this, which mostly involve where the IO happens and whether or not the word list is loaded into memory once or on each access.

solver :: FilePath -> [Char] -> IO [String]
solver path randomLetters = do
    allWords <- getList path
    return $ allMatches randomLetters allWords

The solver returns a list of matches; it's simple to print them by using 'mapM_ putStrLn'. Since this function is printing the strings, not returning them, it's an IO action that returns ():

defaultSolver :: [Char] -> IO ()
defaultSolver randomLetters =
    matches <- solver "/usr/share/dict/words" randomLetters
    mapM_ putStrLn matches

There's still a problem with your randomTiles function unfortunately. Is LettersinWord' is supposed to start with a lowercase letter?

1
votes
solver:: [Char] -> FilePath -> IO [String]
solver letters file = do
    words <- getList file
    return $ filter (flip randomTiles letters) words