我有一组元音:
val vowels = immutable.Set("A", "E", "I", "O", "U", "Y", "a", "e", "o", "u", "y")
我有一套话。我需要检查来自set的第一个单词是否属于元音。
答案 0 :(得分:2)
假设word是一个字符串:
vowels(word.head)
将返回一个布尔值。根据用例,您可以执行以下操作:
words.map(vowels(_.head))
words.filter(vowels(_.head))
答案 1 :(得分:2)
检查一个单词:
scala> vowels.contains("foo".head.toString)
res2: Boolean = false
scala> vowels.contains("oops".head.toString)
res3: Boolean = true
检查List
个字词:
scala> val words = List("foo", "bar", "ate", "elf", "baz")
words: List[String] = List(foo, bar, ate, elf, baz)
scala> words.map(w => vowels.contains(w.head.toString))
res8: List[Boolean] = List(false, false, true, true, false)
您还可以将vowels
定义为Char
,然后在测试中使用toLower
:
scala> val vowels = Set('a', 'e', 'i', 'o', 'u')
vowels: scala.collection.immutable.Set[Char] = Set(e, u, a, i, o)
scala> vowels.contains("Oops".head.toLower)
res18: Boolean = true