You are on page 1of 2

Lab 1

Functional Programming
Start Eclipse and make a new Scala project: File -> New -> Project -> Scala Wizards -> Scala Project -> Next. Give a name la ! and click Finis". #i$"t-click on t"e project in t"e Packa$e Explorer% t"en select Scala -> &reate Scala 'nterpreter. !. a( )ow do *o+ $et t"e s,+ares o- t"e n+m ers -rom ! to !./ ( )ow do *o+ $et t"e s,+ares o- t"e n+m ers -rom ! to !. wit"o+t +sin$ val/ )int: 0non*mo+s -+nctions
le kiem tr 1 so co la so le hay khong 1. Write a -+nction t"at c"eck w"et"er t"e n+m er is odd.

luy thua 2. Write a Scala -+nction pow(x : Double, n : Int) : Double t"at ret+rn a power xn. )int: t"ink rec+rsivel*. For example: pow(2,0) ret+rn 1 pow(2,3) ret+rn 8

3. 4ake a list o- t"e elements !% 1% 2% 5% 6. Write *o+r own -+nctions 7don8t +se Scala li rar* -+nctions: append% reverse(: append(a : List[Int], b : List[Int]) : List[Int] reverse(a : List[Int]) : List[Int] 5. Write a Scala -+nction lessThan t"at ret+rns a list o- all n+m ers > $iven n+m er in a $iven list% -ollowin$ t"e sample code def lessThan(n : Int, lst : List[Int]) ! val fun """ ## $ou% wo%& lst"filte%(fun) ' For example% less()an(*0, List(1, **, +, 2)) *ields List(1,+,2) Finis" less()an -+nction.
9. &+rr* t"e ar$+ments in less()an -+nction so t"at t"e -ollowin$ invocation is le$al:

val filte% val %esult

less()an(3) , filte% (List(1, 2, 3, -, *, +, .) ## List(1, 2)

6. Find o+t a -+nction to: a( &"eck w"et"er a :ist;'nt< "ave some elements e,+al wit" .. ( Select 2 elements -rom t"e t"ird one o- t"e :ist 7i- an*(. For example: List(1,2,3,-,*,+,.,8) / List(3,-,*) c( :ook +p t"e de-inition o- span. 4ake an example t"at demonstrates "ow span works. )int: +se scaladoc% tr* to searc" related -+nctions o- List =. W"at is t"e s"ortest command *o+ can +se to a( #emove all strin$s o- len$t" > 5 -rom a list ( Sort a list o- strin$s * increasin$ len$t" c( Find t"e lon$est strin$ in a list >. )orner?s met"od -or eval+atin$ a pol*nomial +ses -oldin$% like in t"is example: 2x3 0 3x2 1 x 0 * (((2 2 x 0 3) 2 x 1 1) 2 x 0 * Write a -+nction evalPoly(3oeffs : List[Double], x : Double) : Double t"at comp+tes t"e res+lt +sin$ t"e @: operator. For example% eval4ol$(List(2, 3, 11, *), 2) is 31 10. Given lst 6&7t%in8()/ List(1, 2), )ow can we $et a strin$ 5(1 0 2)5 +sin$

11. Write *o+r own code -or t"e -+nction (6axi6u6(lst: List[Int]) : Int) t"at

ret+rns t"e maxim+m o- all elements in a non-empt* list. Ao+ need to write two versions -or t"is -+nction: one +sin$ rec+rsion and t"e ot"er +sin$ -oldin$.

You might also like