Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
F# 使用递归F运行函数#_F# - Fatal编程技术网

F# 使用递归F运行函数#

F# 使用递归F运行函数#,f#,F#,我正在做一些基本的错误,但我不能,为了我的生命,弄清楚它是什么 let rec testItSeveralTimes (test, times) = printfn "Iterations to go %O" times match times with | 0 -> () | _ -> test testItSeveralTime

我正在做一些基本的错误,但我不能,为了我的生命,弄清楚它是什么

    let rec testItSeveralTimes (test, times) =
        printfn "Iterations to go %O" times
        match times with
            | 0 -> ()
            | _ -> 
                test
                testItSeveralTimes (test, (times - 1))

     testItSeveralTimes ((printfn "Running a test"), 2)
我所期望的是:

Iterations to go 2
Running a test
Iterations to go 1
Running a test
Iterations to go 0
Running a test
val it : unit = ()
我得到的是:

Running a test
Iterations to go 2
Iterations to go 1
Iterations to go 0
val it : unit = ()
函数似乎在开始时被计算过一次,然后被忽略


这个问题()似乎有答案,但没有。

这里测试的值为
unit

你想要什么

testItSeveralTimes ((fun _ -> printfn "Running a test"), 2)
并将用法更改为

test()

如果将
test
参数提取到单独的步骤中, 问题变得显而易见:

let test = printfn "Running a test"
// expression has run and printed already!
// value of "test" is a simple value (unit) now
testItSeveralTimes (test, 2)
作为评估
let test=
表达式的一部分,
printfn
函数立即运行

然后,
test
被分配值
()
,该值是
printfn

testitsevertimes
中,test的值就在那里,但并不存在 做任何事

正如John所说,您需要使
test
参数成为可以运行的函数:

let rec testItSeveralTimes (test, times) =
    printfn "Iterations to go %O" times
    match times with
        | 0 -> ()
        | _ -> 
            test()  // test parameter is now a function
            testItSeveralTimes (test, (times - 1))
通过此更改,还需要将
test
值定义为 不会立即运行:

let test() = printfn "Running a test"
// value of test is a function and is not run yet
testItSeveralTimes (test, 2)

一般来说,如果您在理解过程中遇到问题,请尝试将所有步骤分解为如下单独的值--这样更易于调试,因为您可以依次计算每个步骤(在F#Interactive或REPL中)并查看发生了什么

我将其更改为:让rec testitseveratimes(test,times)=printfn“迭代到%O”的时间与| 0->()|->test()testitseveratimes(test,(times-1))testitseveratimes((fun |->printfn)匹配时间“运行一个测试”),2)并且它可以工作,但我不知道为什么。是因为test()强制它作为一个函数进行计算吗?