Skip to content

Instantly share code, notes, and snippets.

@MatrixFrog
Created October 20, 2011 15:39
Show Gist options
  • Save MatrixFrog/1301453 to your computer and use it in GitHub Desktop.
Save MatrixFrog/1301453 to your computer and use it in GitHub Desktop.
Solution to Programming Praxis "Word Breaks" problem
{- 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