2
\$\begingroup\$

Learn You a Haskell shows the words function.

words and unwords are for splitting a line of text into words or joining a list of words into a text

Example:

ghci> words "hey these are the words in this sentence"
["hey","these","are","the","words","in","this","sentence"]
ghci> words "hey these are the words in this\nsentence"
["hey","these","are","the","words","in","this","sentence"]

Please critique my implementation.

words' :: String -> [String]
words' [] = []
words' xxs@(x:xs) 
 | x == ' ' = words' xs
 | otherwise = ys : words' rest
 where (ys, rest) = break (== ' ') xxs
200_success
145k22 gold badges190 silver badges478 bronze badges
asked May 14, 2014 at 0:53
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

words treats any whitespace as a separator, not just spaces. Use Data.Char.isSpace.

It's fine otherwise.

When reimplementing the standard library, you can exploit the standard version as a reference implementation to compare your version to:

map (\x -> words x == words' x) ["", " ", "a", "a ", " a", "a b", "aa bb", "aa\nbb", "a b\nc\td"]
answered May 14, 2014 at 2:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.