2

制御フローを実装gotoするF#の方法に慣れ始めましたがcomefromINTERCALをどのように処理できるかはよくわかりません。

comefromは、ラベルからジャンプできる非常に便利な構成です。次のサンプルプログラムは、これを使用して、手を洗うための完全な手順を印刷します。

comefrom repeat
Console.Write "Lather"
Console.Write "Rinse"
repeat

の美しさは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

私はこれらのプログラムの両方を試しましたが、気まぐれなF#コンパイラーは私を失望させることにしました。comefromF#でどのように利用できますか?

4

3 に答える 3

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())

関数に頭を包み、それ自体が渡されるf関数を受け入れると、それは比較的簡単です。gf

INTERCALコードをF#に移行するのは困難です。これにより、関連する作業が減るはずです。

于 2011-08-24T16:19:50.993 に答える
3

comefromこれは、よりも関数宣言に対応していると思いますgoto

F#のようなことをしている場合goto、ラベルは関数宣言にgoto対応し、コマンドは関数呼び出しに対応します。の場合comefromcomefromコマンドは関数宣言に対応し、ラベルは関数呼び出しに対応します。

関数を使用すると、コードは次のようになります(編集: これは、Ramonがすでに投稿したものと同じですが、追加の説明があるため、ここで回答を保持します):

let rec 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()

コマンドに似た構文を本当に使用したい場合はcomefrom、以下のオプションを確認してください。ただし、その要点はよくわかりません。レガシーコードを適応させる場合は、他の多くのものをF#に変換する必要があり、奇妙な構文を使用すると、F#の慣用句が少なくなります。F#のような新しい実際の構文構造を追加する方法はありません。comefrom

let rec restart = comefrom (fun () ->
  Console.Write "Do you want to restart this program?"
  // (omitted)
  restart())

// where 'comefrom' is just a trivial wrapper for a function
let comefrom f () = f ()

または、計算ビルダーを定義comefromしてから、次の構文を使用することもできます。

let rec restart = comefrom {
  Console.Write "Do you want to restart this program?"
  // (omitted)
  return! restart() }

(このブログ投稿は、適応できる計算ビルダーの非常に簡単な例を示しています)

于 2011-08-24T16:01:10.837 に答える
3
let rec 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()

于 2011-08-24T15:53:10.963 に答える