Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell load external txt file into list

Tags:

haskell

Hello the following code is a wordfeud program. It allows you to search through a list of words matching a prefix, suffix, and some letters. My question is, instead of using the list at the bottom, I want to use a external text file containing the words and load it into the list. How do I go about doing this?

count :: String -> String -> Int
count _[] = 0
count [] _ = 0
count (x:xs) square
    |x `elem` square = 1 + count xs (delete x square)
    |otherwise = count xs square

check :: String -> String -> String -> String -> Bool
check prefix suffix word square
    | (length strippedWord) == (count strippedWord square) = True
    | otherwise = False
    where
        strippedWord = drop (length prefix) (take ((length word ) - (length suffix)) word)


wordfeud :: String -> String -> String -> [String]
wordfeud a b c = test1
    where
    test =["horse","chair","chairman","bag","house","mouse","dirt","sport"]

    test1 = [x| x <- test, a `isPrefixOf` x, b `isSuffixOf` x, check a b x c]
like image 627
tutu Avatar asked Jun 30 '12 20:06

tutu


1 Answers

Very simple, with help of the lines function (or words, when words are seperated by some other form of whitespace than line breaks):

-- Loads words from a text file into a list.
getWords :: FilePath -> IO [String]
getWords path = do contents <- readFile path
                   return (lines contents)

Furthermore, you'll probably have to read up on IO in Haskell (I recommend googling 'io haskell tutorial'), if you haven't done so already. You'll also need it to introduce interactivity into your program.

like image 188
AardvarkSoup Avatar answered Nov 15 '22 11:11

AardvarkSoup