3

( F# コードのリファクタリングに関するこの質問には 1 つ反対票を投じましたが、いくつかの興味深い有用な回答も得られました。また、SO に関する 32,000 以上の質問のうち 62 の F# の質問は哀れに思えるので、さらに不承認になるリスクを負うつもりです!)

昨日、ブロガーのブログにちょっとしたコードを投稿しようとして、過去に役に立ったこのサイトに目を向けました。しかし、ブロガーの編集者はすべてのスタイル宣言を食べてしまったので、それは行き詰まりであることが判明しました。

だから(他のハッカーと同じように)、「どれくらい難しいんだろう?」と思いました。100 行未満の F# で自分自身をロールバックしました。

入力文字列を「トークン」のリストに変換するコードの「要」は次のとおりです。これらのトークンを字句解析/解析スタイルのトークンと混同しないでください。私はそれらを簡単に見ましたが、ほとんど何も理解していませんでしたが、元の文字列を保持したいのに対し、それらがトークンのみを提供することは理解していました.

問題は、これを行うためのよりエレガントな方法はありますか? 入力文字列から各トークン文字列を削除するために必要な s の n 回の再定義は好きではありませんが、コメント、文字列、および #region ディレクティブ (これは単語以外の文字が含まれています)。

//Types of tokens we are going to detect
type Token = 
    | Whitespace of string
    | Comment of string
    | Strng of string
    | Keyword of string
    | Text of string
    | EOF

//turn a string into a list of recognised tokens
let tokenize (s:String) = 
    //this is the 'parser' - should we look at compiling the regexs in advance?
    let nexttoken (st:String) = 
        match st with
        | st when Regex.IsMatch(st, "^\s+") -> Whitespace(Regex.Match(st, "^\s+").Value)
        | st when Regex.IsMatch(st, "^//.*?\r?\n") -> Comment(Regex.Match(st, "^//.*?\r?\n").Value) //this is double slash-style comments
        | st when Regex.IsMatch(st, "^/\*(.|[\r?\n])*?\*/") -> Comment(Regex.Match(st, "^/\*(.|[\r?\n])*?\*/").Value) // /* */ style comments http://ostermiller.org/findcomment.html
        | st when Regex.IsMatch(st, @"^""([^""\\]|\\.|"""")*""") -> Strng(Regex.Match(st, @"^""([^""\\]|\\.|"""")*""").Value) // unescaped = "([^"\\]|\\.|"")*" http://wordaligned.org/articles/string-literals-and-regular-expressions
        | st when Regex.IsMatch(st, "^#(end)?region") -> Keyword(Regex.Match(st, "^#(end)?region").Value)
        | st when st <> "" -> 
                match Regex.Match(st, @"^[^""\s]*").Value with //all text until next whitespace or quote (this may be wrong)
                | x when iskeyword x -> Keyword(x)  //iskeyword uses Microsoft.CSharp.CSharpCodeProvider.IsValidIdentifier - a bit fragile...
                | x -> Text(x)
        | _ -> EOF

    //tail-recursive use of next token to transform string into token list
    let tokeneater s = 
        let rec loop s acc = 
            let t = nexttoken s
            match t with
            | EOF -> List.rev acc //return accumulator (have to reverse it because built backwards with tail recursion)
            | Whitespace(x) | Comment(x) 
            | Keyword(x) | Text(x) | Strng(x) -> 
                loop (s.Remove(0, x.Length)) (t::acc)  //tail recursive
        loop s []

    tokeneater s

(誰かが本当に興味を持っている場合は、残りのコードを投稿させていただきます)

編集kvbによるアクティブパターンの優れた提案を 使用すると、中央のビットは次のようになります。

let nexttoken (st:String) = 
    match st with
    | Matches "^\s+" s -> Whitespace(s)
    | Matches "^//.*?\r?(\n|$)" s -> Comment(s) //this is double slash-style comments
    | Matches "^/\*(.|[\r?\n])*?\*/" s -> Comment(s)  // /* */ style comments http://ostermiller.org/findcomment.html
    | Matches @"^@?""([^""\\]|\\.|"""")*""" s -> Strng(s) // unescaped regexp = ^@?"([^"\\]|\\.|"")*" http://wordaligned.org/articles/string-literals-and-regular-expressions
    | Matches "^#(end)?region" s -> Keyword(s) 
    | Matches @"^[^""\s]+" s ->   //all text until next whitespace or quote (this may be wrong)
            match s with
            | IsKeyword x -> Keyword(s)
            | _ -> Text(s)
    | _ -> EOF
4

1 に答える 1

1

次のように、アクティブなパターンを使用して Regex.IsMatch と Regex.Match のペアをカプセル化します。

let (|Matches|_|) re s =
  let m = Regex(re).Match(s)
  if m.Success then
    Some(Matches (m.Value))
  else
    None

次に、 nexttoken 関数は次のようになります。

let nexttoken (st:String) =         
  match st with        
  | Matches "^s+" s -> Whitespace(s)        
  | Matches "^//.*?\r?\n" s -> Comment(s)
  ...
于 2009-03-26T07:28:13.080 に答える