Hint: it's helpful to know that Instances of the String class are implicitly converted into instances of:
scala.collections.immutable.StringOps
Write and test a simple palindrome detector:
isPal("rotator") //> res0:
Boolean = true
isPal("cat") //>
res1: Boolean = false
isPal("Civic") //> res2:
Boolean = false
isPal("Toyota") //> res3:
Boolean = false
Notes:
· isPal should ignore leading and trailing whitespace.
· It should also be case sensitive.
· It should work even if the string contains characters other than letters.
isPal("$3.1441.3$") //> res4: Boolean = true
Enhance isPal by making a function isPal2 that ignores case, punctuation, and white space:
isPal2("A man, a plan, a canal, Panama!") => true
Hint: filter out undesirable characters, change everything to lowercase, then use the function defined in #1.
Write a random word generator:
val
a1 = mkWord() =>
a1 : String = ltiki
val
a2 = mkWord() =>
a2 : String = iceqy
val
a3 = mkWord() =>
a3 : String = dcjjq
val
a4 = mkWord(20) =>
a4 : String = rlazfucnscevefzaaviv
1. You can specify a default argument for Scala functions:
def mkWord(size: Int = 5) = etc.
Words only contain lowercase letters. The average length should be approximately the average length of words in an English dictionary, which is 5.
2. Before your definition of mkWord type:
import scala.util.Random
Random is Scala's random number generator. It's a pre-defined object, though, not a class.
3. Given a random UNICODE, x, the expression x.toChar will convert it into the corresponding character.
For example:
scala> 0x61.toChar
res4: Char = a
Write a random sentence generator:
val sen1 = mkSentence()
=> sen1 : String = Onbdcevx ldqdhy
xhikrfulbl m dxqfmmkrvy hqvynsxfj gpkak rhpngvigp fqtsaxwiv dong.
val sen2 = mkSentence() => sen2 : String = Usuljsyoo cavtwisgtx jokiodqm ln
zpaeb covr eezi foy odepzev trdofvth.
val sen3 = mkSentence() => sen3 : String = Jbpnwlquh qm r jzeiwi bms z hoyy
qogwgbdmww lqxzuwnj.
val sen4 = mkSentence(5) => sen4 : String = Lsxa fvtqnlz
jnyv xpowyjydoi ltqekjm.
Notes:
· Sentences begin with an uppercase letter and end with a period.
· mkSentence can take an argument, but otherwise uses a default argument of 10.
· Using mkSentence how would you implement mkNovel? mkPoem? mkReply? mkPost?
Write a function that appends the first half of a string to its last half:
shuffle("abcdefghij") = fghijabcde
shuffle("abcdefghijk") =
fghijkabcde
Hint: This would be a good time to learn about the take and drop methods for strings.
Write a function that counts the number of occurrences of a non-empty string in another:
countSubstrings("is", "Mississippi") => 2
Live dangerously, think about making countSubstring recursive!
Complete and test the implementation of the Peano 1.0 console.