F# How to call let function correctly? Function call in [<EntryPoint>] isn't working

你。 提交于 2019-12-11 08:30:23

问题


I am new to F#. What I am trying to do is to call test more than once to print out Hello World. In this example, I want to call test three times. When I run the code it only prints to console once. Even without the test call, it runs. I have the following code:

open System

let test =
    let mutable output = ""
    output <- "Hello World"

    printfn "%s" output

[<EntryPoint>]
let main argv = 
    test
    test
    test
    ignore(Console.ReadKey())
    0 

回答1:


If you want test to be a function, declare it like this:

let test () =

… and call it like this:

test ()

A function always receives one argument and returns one value. Where you see more than one parameter, these are curried into a series of functions that each receive one argument. That's why you see signatures like int -> string -> string.

If you have no need of parameters, as in this case, you use unit, which is represented by ().




回答2:


test as it written is not a function - it is a value of type unit. You have to add parenthesis:

let test () =
    let mutable output = ""
    output <- "Hello World"

    printfn "%s" output

And call it this way:

[<EntryPoint>]
let main argv = 
    test()
    test()
    test()
    ignore(Console.ReadKey())
    0 



回答3:


test is not a function, it's a variable, so you can not call it. You can only access its value, which is (). Accessing a value without doing anything with it does not affect the behavior of the program in any way, which is why writing test in your main function has no effect.

If you want to be able to call test you need to make it a function by giving it a parameter. Since you don't seem to actually want any parameters, you can use unit as the parameter type. That would look like this:

let test () =
    let mutable output = ""
    output <- "Hello World"
    printfn "%s" output

And the corresponding call would look like this:

test ()


来源:https://stackoverflow.com/questions/30103651/f-how-to-call-let-function-correctly-function-call-in-entrypoint-isnt-wor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!