-
Notifications
You must be signed in to change notification settings - Fork 6
Maxim Grishin - Scala test tasks #1
base: master
Are you sure you want to change the base?
Conversation
class Assignment1 { | ||
// Fibonacci sequence | ||
|
||
def fib(n: Int) = fibHelper(0, n, 0, 1) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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]() |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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
)
No description provided.