Followers

Friday, March 2, 2018

Small step towards learning Scala

Q1)To get Out put as mentioned below pattern.
Code Snippet:
(1 to 5).map("*"*_).foreach(println(_))
OutPut:
*
**
***
****
*****
Q2)To get all the even number between two number i.e 1 to 10
Code Snippet:
(1 to 10).filter(_%2==0).foreach(println(_))
Output:
2
4
6
8
10
Q3)One way to find factorial of a number?
Code Snippet:
(1 to 5).reduceLeft(_*_)
or def factorial(n: Int):Int = if(n==0) 1 else n*factorial(n-1)
Output:
120
Q4)Split the string_> sort the string by length,Print in sorted length all word?
input: var s= "Scala supports both object-oriented and functional"
Code Snippet:
s.split(" ").sortWith(_.length<_.length).foreach(println(_))
<--> OutPut:
and
both
Scala
supports
functional
object-oriented
Q5)How to call function inside function,let's suppose we pass one list and one max value and get all the value less then max value from the list? Input:
List:List(9,5,1,4,7,3,8)
Max Vaue:8
Code Snippet:
object Nest extends App{
| def fun1(l:List[Int],max:Int)={
| def fun2(m:List[Int]):List[Int]=
| if(m.isEmpty) m
| else if(m.head | else fun2(m.tail)
| fun2(l)
| }
| println(fun1(List(9,5,1,4,7,3,8),5))
| }

Invocation:<-->
Nest.fun1(List(9,5,1,4,7,3,8),8)
Output:
List[Int] = List(5, 1, 4, 7, 3)

No comments:

Post a Comment