Code - please tell error (its Done)

ListHigherOrderFunction takes an integer input from command line. Based on the input, write a code to generate a list intList, upto a given integer starting from 1. When input is 3, List(1,2,3) must be generated. Write a function factorial which gives the factorial of a given number using recursion. Write a higher order function myHigherOrderFunction which takes factorial function and intList, and prints the factorial of each integer in the intList

I have done the following code:…

object ListHigherOrderFunction{
def main(args :Array[String]){
val input = args(0).toInt
val intList :List[Int]=List.tabulate(3)(n=>n+1)
def factorial(n:Int): Int=
if(n == 1) 1
else n * factorial(n - 1)

def myHigherOrderFunction(factorial:()=>Int,list:List[Int]){
val result = for(i<-list){factorial(i)}
myHigherOrderFunction(factorial, intList)

below is the error:…

$ scalac ListHigherOrderFunction.scala
ListHigherOrderFunction.scala:12: error: too many arguments for method apply: ()Unit in trait Function0
val result = for(i<-list){factorial(i)}
ListHigherOrderFunction.scala:17: error: type mismatch;
found : Int => Int
required: () => Unit
myHigherOrderFunction(factorial, intList)
two errors found

There are a few errors:

  • I think you mean def myHigherOrderFunction(factorial:Int=>Int,list:List[Int]) not () => Int.
  • the for should be val result = for (i <- list) yield factorial(i), i.e., you need the yield otherwise for desugars to foreach (see docs).
  • You should return the intList, which means the last line of the function should be just result, not println(result).
  • Not a logical error, but in your higher order function, factorial is a variable name, which becomes a peculiar choice (and confusing if your code is larger). Better to call it f.
  • There may be more errors but fix these first.
  • Finally, the last time I replied I requested you to use fenced code blocks, i.e., begin and end your code with three backtick symbols on separate lines (google for details). It is annoying that you still are not doing this, and if you annoy people the chance that they will help decreases.


1 Like

Thankyou sir,I got it.

Please give example how to use fenced code block , I tried on google but it saying that use backtick . If it so then next time I will used that backtick as well.or I request you to please give one exampe to make me more clarify.

Just see the documentation for fenced code blocks on github.


ok sir,I got it.Next time I will apply.
Thank you