[Haskell-cafe] Hi I need help for very simple question!
Bryan Donlan
bd.haskell at uguu.us
Sat Mar 3 02:02:00 EST 2007
Taillefer, Troy (EXP) wrote:
> Hi there
>
> 1. First of all never forget your base case for exiting your recursion
> 2. you need to break up the problem like so
>
>
> import Char
>
> -- get the first word
> word :: String -> String
> word [] = []
> word ( x : x1 : xs )
> | isSpace x = []
> | isSpace x1 = x : []
> | otherwise = x : x1 : word(xs)
>
> -- get everything but the first word
> rest :: String -> String
> rest [] = []
> rest ( x : x1 : xs )
> | isSpace x = x1 : xs
> | isSpace x1 = xs
> | otherwise = rest(xs)
>
> intoWords :: String -> [ String ]
> intoWords [] = []
> intoWords ws = word(ws) : words( rest(ws) ) -- glue the first word and
> call recursively on the rest
Personally, I think it's a bit clearer to use dropWhile and span:
import Data.List
import Data.Char
mywords :: String -> [String]
mywords string
| word == ""
= []
| otherwise
= word:mywords remain
where
(word, remain) =
span (not . isSpace) . dropWhile isSpace $ string
More information about the Haskell-Cafe
mailing list