[Haskell-beginners] Re: Defining 'words' in terms of 'span'
Daniel Fischer
daniel.is.fischer at web.de
Tue Mar 16 17:22:23 EDT 2010
Am Dienstag 16 März 2010 21:54:24 schrieb Tim Attwood:
> "Roger Whittaker" <roger at disruptive.org.uk> wrote in message
> news:20100316170815.GA19787 at disruptive.org.uk...
>
> >I found some exam papers linked from this page:
> > http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/external.html
> >
> > And I have been trying some questions from them.
> >
> > I'm currently baffled by question 2(b) on this one:
> > http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/tenta2000-04.p
> >s
> >
> > A word is a sequence of alphabetic characters, which you can
> > recognise using the standard function
> >
> > isAlpha :: Char -> Bool
> >
> > Using span, define a function words :: String -> [String] which
> > finds a list of the words occurring in a string. For example,
> >
> > words "Now is the winter of our discontent!"
> > == ["Now","is","the","winter","of","our","discontent"]
> >
> > words "2+3" == []
> >
> > words "1 by 1" == ["by"]
> >
> > Can anyone give me a clue how to start?
>
> words' = filter (all isAlpha) . words
Prelude> words' "Now is the winter of our discontent!"
["Now","is","the","winter","of","our"]
Maybe you thought of
words'' = map (filter isAlpha) . words
, but that doesn't do the required thing for e.g.
"oops,forgot the space after the comma!"
>
> ...but since they specifically want span in the answer I'd guess they
> want some sort of recursive function
Sure. At the bottom, such a function must use recursion. The question is,
can you employ some combinators like fold*, or do you have to recur
explicitly.
>
> words' s = wGen s [] where
> wGen s a =
> let (n,ws) = span (\x -> not (isAlpha x)) s
> (w,ss) = span (isAlpha) ws
> in case (w=="",ss="") of
> True, _ -> reverse a
> False, True -> reverse (w:a)
> False, False -> wGen ss (w:a)
>
> something ugly like that maybe.
>
More like
words' s = case span isAlpha (dropWhile (not . isAlpha) s) of
("",_) -> []
(w,rest) -> w:words' rest
More information about the Beginners
mailing list