0

I am trying to loop a the second parameter (exp) in this function that uses call by name parameters. The first 3 parameters are the index, boolean to stop loop, and increment function. I am getting an output with 10 '()'s when I am trying to loop "hello world" 10 times as seen in the test code. May I get some help with what is wrong here? Thanks

def forLoop(ival: => Int, f: (Int) => Boolean, g: (Int)=>Int)(exp: => Unit): Unit = {
  if(f(ival)==false) 
    return
  else {
    println(exp)
    forLoop(g(ival),f,g)(exp)
  }
}

def f(x: Int): Boolean = { x<10 }
def g(y: Int): Int = { y+1 }
val exp: Unit = "Hello World"
forLoop(0,f,g)("Hello World")
3
  • Also I think I formatted the parameter functions f and g when trying to use call by name but I am not sure. Commented May 29, 2020 at 0:15
  • I have changed it to return Unit and changed return true to just return in the base case. My bad. Sorry I am new Commented May 29, 2020 at 0:46
  • ok i have updated Commented May 29, 2020 at 0:55

2 Answers 2

2

The value "Hello World" is of type String however you are assigning it to Unit

val exp: Unit = "Hello World"

which compiler expands to

val exp: Unit = {
  "Hello World";
  ()
}

Note how () becomes the value of exp. Try changing the definition of exp to

val exp: String = "Hello World"

and second parameter list to

(exp: => String)

If you compile with compiler flag -Wvalue-discard, for example,

scala -Wvalue-discard -e 'val exp: Unit = "Hello World"'

you will get a warning

warning: discarded non-Unit value
val exp: Unit = "Hello World"
                ^
Sign up to request clarification or add additional context in comments.

2 Comments

I get the same result even when I declare val exp: String = "Hello World"
Oh, my I am required to have the second parameter as Unit
2

I think this meets your requirements.

def forLoop(ival: => Int, f: =>Int => Boolean, g: =>Int=>Int
           )(exp: => Unit): Unit =
  if (f(ival)) {
    exp
    forLoop(g(ival),f,g)(exp)
  }

def f(x: Int): Boolean = x<10
def g(y: Int): Int = y+1
def exp: Unit = println("Hello World")
forLoop(0,f,g)(exp)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.