Программирование на языке Scala/Кортеж/Ответы
Внешний вид
(перенаправлено с «Программирование на языке Scala/Кортеж/Кортеж Ответы»)
2.
val splitFun: (String, Char) => (String, String) =
(str, char) => {
val firstPart = str.takeWhile(c => c != char)
val secondPart = str.dropWhile(c => c != char)
firstPart -> secondPart.tail
}
3.
val tailFun: String => String =
str =>
str.foldLeft(("", true))( (acc, el) => {
val (res, isHead) = acc
if (isHead)
(res, false)
else
(res + el, false)
})._1
4.
val takeFun: (String, Int) => String =
(str, num) =>
str.foldLeft(("", 0))((acc, el) => {
val (res, strIndex) = acc
if (strIndex < num)
(res + el, strIndex + 1)
else
(res, strIndex + 1)
})._1
5.
val dropFun: (String, Int) => String =
(str, num) =>
str.foldLeft(("", 0))((acc, el) => {
val (res, strIndex) = acc
if (strIndex < num)
(res, strIndex + 1)
else
(res + el, strIndex + 1)
})._1
6.
val initFun: String => String =
str =>
str.foldLeft(("", 0))((acc, el) => {
val (res, strIndex) = acc
if (strIndex < str.length - 1)
(res + el, strIndex + 1)
else
(res, strIndex + 1)
})._1
7.
val indexOfFun: (String, String) => Int =
(str, pattern) => {
if (pattern.isEmpty || str.isEmpty || (pattern.length > str.length))
-1
else {
val resTuple = str.foldLeft((0, 0, false))((acc, el) => {
val (strIndex, patternIndex, isSuccess) = acc
if (isSuccess)
(strIndex, patternIndex, true)
else
if (el == pattern(patternIndex)) {
if (patternIndex < pattern.length - 1)
(strIndex + 1, patternIndex + 1, false)
else
(strIndex - patternIndex, patternIndex, true)
}
else
(strIndex + 1, 0, false)
})
if (resTuple._3)
resTuple._1
else
-1
}
}