How to simplify this Scala Fibonacci code, which returns the sixth digit? -


The purpose of the application is to display a number sequence and the user has to select the sixth digit:

1 2 3 5 8 ...

However, to check the application's demands, another code was to be created, i.e. the sixth digit number of the sequence.

Test

Import org.scalatest.FunSuite Import org.scalatest.FunSpec Import org.scalatest.matchers.ShouldMatchers Class Calculation Test FenSuit {Test ("fibonacci") {emphasis (calculation. Fibonacci (1, 2) === 13)}}

main

< Pre> object calculation {EFFibonaceae (A: IIT, B: IT): IT = {vir first: int = one var second: IT = b preferred third: int = 0 second fourth: int = 0 fifth: int = 0 viral sixth: int = 0 third = first + second fourth = second + it Ra = Fifth Third + Fourth sixth = fourth + fifth comeback sixth}} What

The main code is possible to simplify, eg. Just doing the return of the sixth digit, instead of comparing each individual issue?

You can define the sequence as infinite laziness Will not:

  Scala> Lazy Val Fibs: Stream [int] = 1 #: Fibsskan Left (2) (_ + _) Fibers: stream [int] = & lt; Lazy & gt;  

Then you can only ask for 6th item, which only emphasizes calculation of the first 6 items:

  scala> Fibs (5) res0: Int = 13  

Or you can ask for the first 6:

  scala> Fibs.take (6) res1: scala.collection.immutable.Stream [int] = stream (1,?)  

But keep in mind that it is still working lazy, you They can be compelled to compute:

  Scala> Fibs.take (6). Force res2: scala.collection.immutable.Stream [int] = stream (1, 2, 3, 5, 8, 13) or simply result in one list:  
  Scala> Fibs.take (6) .tolist res3: list [int] = list (1, 2, 3, 5, 8, 13)  

Comments

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

c# - Create dynamic LINQ query expression at runtime which translates into a parameterized SQL query for nullable types -

cmake - cpack generates RPMs with %files entries that conflict with the RPM spec. How to fix? -