Not sure what is wrong in below code

Declare an implicit integer variable 5. Generate a List with input1 such that the number of elements is equal to input1 , and the numbers are from 1 to input1 (when input is 3 -> List(1,2,3)). Write a curried function add which takes two integer variables in which one variable is an implicit variable. Using a for comprehension , apply the add function on the generated list and print the result.

for above requirement, i have done below code and got the desired output as well but my lab exercise is not completing. not sure what is wrong, please help to suggest the changes in below code if any so that Lab exercise can be marked as completed.

object Demo extends App {
val input1 :Int = args(0).toInt
//complete the code
implicit val test = 5
val list = List.range(1, input1+1)
def add(x : Int)(implicit y: Int = 5) = x + y
println(add(list(1)))
println(add(list(2)))
println(add(list(3)))
}

Clearly, you have:

  • not used for comprehension.
  • ignored input1 when it comes to writing.

A part of you code should be of the form (replace ??? by whatever is appropriate)

for {i <- 1 to input1} ???

And finally, for the last time, PLEASE google search for “fenced code block” and use it before you post again. It makes it easier for those who answer your questions, and the least you can do is make that bit of effort.

regards,
Siddhartha

2 Likes

You can try as below it should work.

object Demo extends App {
val input1 :Int = args(0).toInt
implicit val test = 5
val list = List.range(1, input1+1)
def add(x : Int)(implicit y: Int) = x + y
for(i <- list) {
println(add(i))
}
}

object Demo extends App{
var input1 = args(0).toInt
implicit val a = 5
val inList = List.tabulate(input1)(n=>(n+1))
println(“Output will be:”)
for(i<-inList){
def add(implicit x:Int, y:Int) = x + i
val sum = add
println(sum)
}
}

This works perfectly fine.