This competition was run on #scala. The task is to write a short def capWord which checks whether a given string is a Capital word. Some entries follow.
@paulp I:
def capWord(s: String) = (s.tail map (_.isLowerCase))
.reduceLeft(_ && _) && s.head.isUpperCase
— and he notes: of course that fails on “P”. but maybe that’s not a word either. more of a letter.
@paulp II:
def capWord(s: String) = !s.isEmpty &&
(s.head isUpperCase) && (s.tail forall (_.isLowerCase))
— and he notes: I won’t deal with null out of spite.
@RShulz:
def capWord(word: String): Boolean =
{ word.count(_.isUpperCase) == 1 && word(0).isUpperCase }
— and he notes: (Count exists in my mind.)
@dcsobral I, the winning entry (no head or tail, and I like it):
def capWord(w: String) = w.toList match {
case h :: t if ('A' to 'Z' contains h) &&
(t forall ('a' to 'z' contains _)) => true
case _ => false
}
@dcsobral II, the fold entry:
def capWord(w: String) = w.tail.foldLeft(w.head isUpperCase)
( (flag, l) => flag && l.isLowerCase )
@dcsobral III, fanciful entry:
def capWord(w: String) = (
(
w
map (_ isUpperCase)
map (if (_) 1 else 0)
zipWithIndex
)
map Function.tupled((a,b) => a * (b+1))
reduceLeft (_+_)
) == 1
@SethTisue, mindboggling entry:
def capWord(s: String) =
(Math.log(s.map(c =>
if(c.isUpperCase) 1 else 0).mkString.toDouble)
/ Math.log(10)).toString.endsWith(".0")
@paulp III, the mondblowingboggling entry:
def capWord(s: String) = s.head.isUpperCase &&
(s.tail map (c =>
io.Source.fromURL(new java.net.URL("http://www.simplyscala.com/interp?code='%s'.isLowerCase"
.format(c.toChar.toString))).mkString)
forall (_ contains "true"))
— and he notes: I could use threads to speed that up a little.