你如何在F#中实现comefrom?

Pet*_*son 2 f# comefrom

我已经开始习惯于实现goto控制流的F#方式了,但是我不太清楚我是如何处理的comefrom,这是一个INTERCAL.

comefrom是一个非常有用的结构,允许您从标签跳转.以下示例程序使用它来打印洗手的完整说明:

comefrom repeat
Console.Write "Lather"
Console.Write "Rinse"
repeat
Run Code Online (Sandbox Code Playgroud)

美丽的comefrom是你可以在多个地方贴上标签.

comefrom restart
Console.Write "Do you want to restart this program?"
let a = Console.ReadLine()
match a with
| "Y" -> restart
| _   -> Console.Write "Too bad! It will restart whether you like it or not!"
         restart
Run Code Online (Sandbox Code Playgroud)

我尝试了这两个程序,但反复无常的F#编译器决定让我失望.我怎样才能利用comefromF#?

Dan*_*iel 5

这非常接近您想要的语法.

let comefrom f = 
  let rec g = (fun () -> f g)
  f g

comefrom (fun restart ->
  Console.Write "Do you want to restart this program?"
  let a = Console.ReadLine()
  match a with
  | "Y" -> restart()
  | _   -> Console.Write "Too bad! It will restart whether you like it or not!"
           restart())
Run Code Online (Sandbox Code Playgroud)

一旦你绕过一个函数,f接受一个函数g,它本身被传递给f它,它是相对简单的.

将INTERCAL代码迁移到F#很难.这有望减少所涉及的工作.