Skip to content
This repository was archived by the owner on Sep 22, 2022. It is now read-only.

Maxim Grishin - Scala test tasks #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Igevorse
Copy link

No description provided.

class Assignment1 {
// Fibonacci sequence

def fib(n: Int) = fibHelper(0, n, 0, 1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solution is good! But it is possible to improve style. You can use pattern matching instead of if. You can move n: Int to be the first argument and set default values for other arguments, so we can call fibHelper like that: fibHelper(n)


// Prime numbers

def prime(n: Int): Int = primeHelper(n, 0, 1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool! Same comments on style as for fib. You can improve code with Sieve of Eratosthenes and there is a really functional implementation using that approach, it involves usage of Stream since scala affords
infinite lists through Stream

// High order functions - 2 - map

def map[A, B](f: A => B, l: List[A]): List[B] = l match {
case head :: tail => List[B](f(head)) ::: map(f, tail)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is more efficient to just do f(head) :: map(f, tail) because concatenation ::: requires whole list traversal


def map[A, B](f: A => B, l: List[A]): List[B] = l match {
case head :: tail => List[B](f(head)) ::: map(f, tail)
case Nil => List[B]()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lists constructed as:
Nil or el :: List
so you can return just Nil instead of ListB

// High order functions - 5 - filter and map revisited

def foldMap[A, B](f: A => B, l: List[A]): List[B] =
foldLeft(List[B](), (b: List[B], a: A) => b ::: List[B](f(a)), l)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You also can pass Nil as an acc. Also you can consider f(a) :: b instead of b ::: List[B](f(a)), but in this case you should reverse list at the end

case object Zero extends Nat
case class Succ(n: Nat) extends Nat

def add(a: Nat, b: Nat): Nat = (a, b) match {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is possible to define this function with two cases too (as sub)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants