简体   繁体   English

在函数内部调用函数后,如何在F#中重复该函数?

[英]How can I repeat functions in F# after a function has been called inside it?

I have a game where you can do certain actions, then after the action is done I have a list of actions you can do again but after it's been completed once the program ends, I thought because it's a recursive function it will keep going. 我有一个游戏,您可以执行某些操作,然后在完成操作后,我会列出您可以再次执行的操作,但是一旦程序结束,完成操作后,我认为因为它是递归函数,所以它将继续进行。

This is not part of my game but just a demonstration, this program asks for a string once then finishes. 这不是我的游戏的一部分,而只是一个演示,该程序要求输入一个字符串然后完成。 Shouldn't it keep asking for a string, and how can I make it do that? 它不应该继续要求一个字符串吗,我该怎么做呢? I also tried calling back to the recursive function inside the f1 function but of course f1 does not know it exists. 我还尝试了回调f1函数内部的递归函数,但是f1当然不知道它的存在。

open System

let f1 x =
    printfn "Hello, %s" x

let rec f2 =
    let x = Console.ReadLine()
    f1 x

Console.Read() |> ignore

As noted in the comments, you define f2 as a value, not as a function. 如注释中所述,您将f2定义为一个值,而不是一个函数。 This has been discussed on StackOverflow before and there is a good question and answer that covers this. 之前已经在StackOverflow上对此进行了讨论,对此有一个很好的问答。

The other problem is that you probably want to call f2 from f1 (to continue looping) as well as call f1 from f2 . 另一个问题是您可能想要从f1调用f2 (以继续循环)以及从f2调用f1 To do this, you can define the functions as mutually recursive using let rec .. and syntax: 为此,您可以使用let rec .. and语法将函数定义为相互递归:

let rec f1 x =
    printfn "Hello, %s" x
    f2 ()

and f2 () =
    let x = Console.ReadLine()
    f1 x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM