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 - Шамала Александр #276

Open
wants to merge 1 commit 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
34 changes: 30 additions & 4 deletions homeworks/homework_9/src/main/scala/ListOps.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import DataList.EmptyList

import scala.annotation.tailrec

object ListOps {
Expand All @@ -9,7 +11,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 DataList.NonEmptyList(head, tail) => foldOption(f)(tail) match {
case Some(value) => Some(f(head, value))
case None => Some(head)
}
case DataList.EmptyList => None
}


/**
Expand All @@ -22,15 +30,31 @@ object ListOps {
*/
def sumT(a: T, b: T) = implicitly[Numeric[T]].plus(a, b)

???
foldOption(sumT)(list).getOrElse(implicitly[Numeric[T]].zero)
}

/**
* Фильтрация списка. Хвостовая рекурсия
* @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 DataList.EmptyList => reverse(buffer)(DataList.EmptyList)
case DataList.NonEmptyList(head, tail) => f(head) match {
case true => filterImpl(f)(DataList.NonEmptyList(head, buffer))(tail)
case false => filterImpl(f)(buffer)(tail)
}
}
}

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

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

Expand All @@ -43,6 +67,8 @@ 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] = {
dataList => map(f)(filter(f.isDefinedAt)(dataList))
}

}