On Fri, Jun 17, 2011 at 12:58 AM, Ryan Twitchell <metatheo...@gmail.com> wrote:
> Just for reflection:
> What would you do with an existing class which had a getName() method,
> when you suddenly realized you wanted getFirstName() and getLastName()
> instead?  Or the reverse?

If you can't refactor the class, that's a relatively simple one to
solve with helper methods/functions:

(defn word-seq [s]
  (map (partial apply str) (take-nth 2 (partition-by
#(Character/isWhitespace %) s))))

(defn is-not-capitalized [w]
  (Character/isLowerCase (first w)))

(defn get-name [first last]
  (str first " " last))

(defn get-first-name [full]
  (first (word-seq full)))

(defn get-last-name [full]
  (let [chunks (reverse (drop 1 (word-seq full)))]
    (apply str
      (interpose " "
        (reverse
          (cons
            (first chunks)
            (take-while is-not-capitalized (rest chunks))))))))

=> (get-name "Bob" "Marley")
"Bob Marley"
=> (get-first-name "Bob Marley")
"Bob"
=> (get-last-name "Bob Marley")
"Marley"
=> (get-last-name "Sarah Michelle Gellar")
"Gellar"
=> (get-last-name "Frederique van der Wal")
"van der Wal"
=> (get-last-name "Olivia d'Abo")
"d'Abo"

The only slightly tricky one is get-last-name, since some last names
are more than one word and these need to be distinguished from middle
names. Fortunately, these last names only seem to capitalize the last
chunk. The last three examples use three famous actresses' names to
demonstrate that it drops middle names, keeps multi-part surnames, and
keeps surnames that start with a noncapitalized letter but are only
one part.

Of course there may be some more obscure corner case that isn't
covered, and if the input is incorrectly capitalized or spaces are
missing, all bets are off.

Names with only one chunk are presumed to be first names, so
get-first-name returns the whole input and get-last-name an empty
string in those cases.

Note how the above is clean sequence-manipulation code without a
single ugly regexp in sight.

-- 
Some people, when confronted with a problem, think “I know, I'll use
regular expressions.”
Now they have two problems.
- Jamie Zawinski

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to