Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

homework_9 - Тебайкин Максим #264

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions homeworks/homework_9/src/main/scala/ListOps.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import DataList.{EmptyList, NonEmptyList}

import scala.:+
import scala.annotation.tailrec

object ListOps {
Expand All @@ -9,7 +12,13 @@ object ListOps {
* @param f функция свёртывания. Применяется попарно к предыдущему результату применения и i-ому элементу списка
* @return None - если список пустой
*/
def foldOption[T](f: (T, T) => T): DataList[T] => Option[T] = ???
def foldOption[T](f: (T, T) => T): DataList[T] => Option[T] = {
case NonEmptyList(head, tail) => foldOption(f)(tail) match {
case Some(value) => Some(f(head, value))
case None => Some(head)
}
case EmptyList => None
}


/**
Expand All @@ -21,16 +30,26 @@ object ListOps {
* Используйте для суммирования двух чисел любого типа (Int, Long, Double, Float etc)
*/
def sumT(a: T, b: T) = implicitly[Numeric[T]].plus(a, b)
foldOption(sumT)(list).getOrElse(Numeric[T].zero)
}

???
@tailrec
def reverse[T](l: DataList[T], buffer: DataList[T]): DataList[T] = l match {
case NonEmptyList(head, tail) => reverse(tail, NonEmptyList(head, buffer))
case EmptyList => buffer
}

/**
* Фильтрация списка. Хвостовая рекурсия
*
* @param f - фильтрующее правило (если f(a[i]) == true, то элемент остаётся в списке)
*/
@tailrec
private def filterImpl[T](f: T => Boolean)(buffer: DataList[T])(l: DataList[T]): DataList[T] = ???
private def filterImpl[T](f: T => Boolean)(buffer: DataList[T])(l: DataList[T]): DataList[T] = l match {
case EmptyList => reverse(buffer, EmptyList)
case NonEmptyList(head, tail) =>
filterImpl(f)(if (f(head)) NonEmptyList(head, buffer) else buffer)(tail)
}

final def filter[T](f: T => Boolean): DataList[T] => DataList[T] = filterImpl(f)(DataList.EmptyList)

Expand All @@ -43,6 +62,6 @@ object ListOps {
* Используя композицию функций реализуйте collect. Collect - комбинация filter и map.
* В качестве фильтрующего правила нужно использовать f.isDefinedAt
*/
def collect[A, B](f: PartialFunction[A, B]): DataList[A] => DataList[B] = ???
def collect[A, B](f: PartialFunction[A, B]): DataList[A] => DataList[B] = filter(f.isDefinedAt).andThen(map(f))

}