Search code examples
f#fsiunit-type

Printfn value is not a function and cannot be applied in F#'s interactive window


This is probably something simple, but I have a .fs file with a simple sample function.

let printHello = printfn "%A" "Hello"

I have set the search path to the .fs file using

>#I "PathToMyFSFile"

I have loaded my file using

>#load "Test.fs"

Which worked fine. Now I want to call the function which actually prints the hello to screen, but thats turning out to be too difficult

> Test.printHello;;
val it : unit = ()

Tried Test.printHello();; as well but doesn't work. How do I actually make it print "Hello" to screen?


Solution

  • your current printHello isn't actually a function. To make it a function you need to do

    let printHello() = printfn "%A" "Hello"
    

    noice the (). Then everything should work.

    EDIT:

    When the compiler sees your definition

    let printHello = printfn "%A" "Hello"
    

    it passes it as a simple data term. For example, consider this program:

    let printHello = printfn "%A" "Hello"
    printfn "World"
    printHello
    

    This will print "Hello" then "World". printHello just has unit type, so does nothing. Compare it to

    let printHello() = printfn "%A" "Hello"
    printfn "World"
    printHello()
    

    Here printHello is a function. In this case, the function is only executed when it is explicitly called, so this prints "World" then "Hello".