0

I have this code:

Scala:

object C extends App{
 def a(): Unit ={
   println("a")
  }

  val b=a
}

f#:

let a=printfn "%A" "a"

[<EntryPoint>]
let main argv = 
  let b=a
  0 // return an integer exit code

I only want to pass the function as a value a, not to run it. Why, when I run the program, I get "a" written to the console?

jwvh
  • 50,871
  • 7
  • 38
  • 64
wang kai
  • 1,673
  • 3
  • 12
  • 21
  • 1
    In F# code you need to make `a` a function to work as you expect. Currently it's a value that is calculated when you assign it to `b`. So just add (): `let a() =printfn "%A" "a"` – 3615 Jun 12 '19 at 07:33

4 Answers4

3

In the Scala code a() is a method. As such it cannot be passed as an argument or assigned as a value, but it can be tuned into a function, via eta-expansion, which can be passed as an argument and/or assigned as a value.

val b = a _
jwvh
  • 50,871
  • 7
  • 38
  • 64
2

If you want a to be a function you need to give it parameters:

let a () = printfn "%A" "a"

then call it in main:

let main argv = 
  let b = a ()
  0 // return an integer exit code
Lee
  • 142,018
  • 20
  • 234
  • 287
2

Adding on to jwvh 's answer, the spirit of your F# code may be more accurately represented by defining a as a function instead of a method:

val a = () => println("a")

val b = a

This will work as intended, no eta expansion required.

Astrid
  • 1,808
  • 12
  • 24
0

b is evaluated when that line is of your code is reached.

try using lazy instead. this will calculate the value of b only when you call it.

object C extends App{
 def a(): Unit ={
  println("a")
 }

 lazy val b = a // Nothing will happen here
 b // Now "a" will be printed
}
Dionysis Nt.
  • 955
  • 1
  • 6
  • 16