Created
October 20, 2011 15:39
-
-
Save MatrixFrog/1301453 to your computer and use it in GitHub Desktop.
Solution to Programming Praxis "Word Breaks" problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- http://programmingpraxis.com/2011/08/12/word-breaks/ | |
Given an input string and a dictionary of words, | |
segment the input string into a space-separated | |
sequence of dictionary words if possible. For | |
example, if the input string is "applepie" and | |
dictionary contains a standard set of English words, | |
then we would return the string "apple pie" as output. | |
-} | |
{- Usage: | |
λ>split "anapplepie" | |
Just ["an","apple","pie"] | |
λ>split "anxapplexpie" | |
Nothing | |
-} | |
import Control.Monad (msum) | |
-- implement the "dictionary" as a simple function: | |
isWord :: String -> Bool | |
isWord "apple" = True | |
isWord "pie" = True | |
isWord "app" = True | |
isWord "pile" = True | |
isWord "a" = True | |
isWord "an" = True | |
isWord _ = False | |
divide :: String -> [(String, String)] | |
divide s = map f [1..length s] | |
where f n = splitAt n s | |
split :: String -> Maybe [String] | |
split "" = Nothing | |
split s | isWord s = Just [s] | |
| otherwise = msum $ map tupleToSolution (divide s) | |
where tupleToSolution :: (String,String) -> Maybe [String] | |
tupleToSolution (a,b) = | |
if isWord a | |
then split b >>= return . (a:) | |
else Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment