The Artima Developer Community
Sponsored Link

Java Buzz Forum
words with fold

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Elliotte Rusty Harold

Posts: 1573
Nickname: elharo
Registered: Apr, 2003

Elliotte Rusty Harold is an author, developer, and general kibitzer.
words with fold Posted: Jan 26, 2009 11:38 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Elliotte Rusty Harold.
Original Post: words with fold
Feed Title: Mokka mit Schlag
Feed URL: http://www.elharo.com/blog/feed/atom/?
Feed Description: Ranting and Raving
Latest Java Buzz Posts
Latest Java Buzz Posts by Elliotte Rusty Harold
Latest Posts From Mokka mit Schlag

Advertisement

Real World Haskell, Exercise 10, p. 98: Write the words function using list folds:

myWords :: String -> [String]
myWords s = reverse (foldr step [] (trim s))

step :: Char -> [String] -> [String]
step c [] = [c:[]]
step c acc
    | (isSpace c) = acc ++ [""]
    | otherwise = (take ((length acc) - 1) acc) ++ [c:(last acc)]

isSpace :: Char -> Bool
isSpace ' '  = True
isSpace '\n' = True
isSpace '\r' = True
isSpace '\t' = True
isSpace _    = False

lstrip :: String -> String
lstrip [] = ""
lstrip (x:xs)
  | (isSpace x) = lstrip xs
  | otherwise = x:xs

rstrip :: String -> String
rstrip s = reverse (lstrip (reverse s))

trim :: String -> String
trim = lstrip . rstrip

Moral of this exercise: you can only pass a list to ++. You can’t use ++ to append a Char to a String. You have to append [c] instead.

There’s probably an isSpace function in the standard library somewhere I could be using instead. (Found it. It’s Char.isSpace)

The trim function feels unnecessary. A more clever implementation of the fold might avoid it.

And that reverse is really yucky. I should be able to rewrite the fold so the values come out in the right order.

Read: words with fold

Topic: I've posted the third beta of XOM 1.2, my free-as-in-speech (LGPL) library for processing XML... Previous Topic   Next Topic Topic: Windows 7 Tricks: How to Enable or Disable Services in Windows 7

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use