我正在将一些OCaml代码转换为F#,因为OCaml let...and...
存在问题,它只存在于F#中,使用递归函数。
我有给定的OCaml代码:
let matches s = let chars = explode s in fun c -> mem c chars
let space = matches " \t\n\r"
and punctuiation = matches "() [] {},"
and symbolic = matches "~'!@#$%^&*-+=|\\:;<>.?/"
and numeric = matches "0123456789"
and alphanumeric = matches "abcdefghijklmopqrstuvwxyz_'ABCDEFGHIJKLMNOPQRSTUVWXYZ"
我想在这两种方法中使用:
let rec lexwhile prop inp = match inp with
c::cs when prop c -> let tok,rest = lexwhile prop cs in c+tok,rest
|_->"",inp
let rec lex inp =
match snd(lexwhile space inp)with
[]->[]
|c::cs ->let prop = if alphanumeric(c) then alphanumeric
else if symbolic(c) then symbolic
else fun c ->false in
let toktl,rest = lexwhile prop cs in
(c+toktl)::lex rest
有人知道我必须如何更改它以便我可以使用它吗?
答案 0 :(得分:7)
您似乎正在尝试翻译“Handbook of Practical Logic and Automated Reasoning”。
您看到了:An F# version of the book code现已推出!感谢Eric Taucher,Jack Pappas和Anh-Dung Phan。
您需要查看intro.fs
// pg. 17
// ------------------------------------------------------------------------- //
// Lexical analysis. //
// ------------------------------------------------------------------------- //
let matches s =
let chars =
explode s
fun c -> mem c chars
let space = matches " \t\n\r"
let punctuation = matches "()[]{},"
let symbolic = matches "~`!@#$%^&*-+=|\\:;<>.?/"
let numeric = matches "0123456789"
let alphanumeric = matches "abcdefghijklmnopqrstuvwxyz_'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let rec lexwhile prop inp =
match inp with
| c :: cs when prop c ->
let tok, rest = lexwhile prop cs
c + tok, rest
| _ -> "", inp
let rec lex inp =
match snd <| lexwhile space inp with
| [] -> []
| c :: cs ->
let prop =
if alphanumeric c then alphanumeric
else if symbolic c then symbolic
else fun c -> false
let toktl, rest = lexwhile prop cs
(c + toktl) :: lex rest
我在处理翻译时问了很多questions,并用Converting OCaml to F#:
作为前缀。如果您查看评论,您将看到我们三个人如何参与此项目。
答案 1 :(得分:3)
你可以写:
let explode s = [for c in s -> string c]
let matches str strc =
let eStr = explode str
List.contains strc eStr
let space = matches " \t\n\r"
let punctuation = matches "() [] {},"
let symbolic = matches "~'!@#$%^&*-+=|\\:;<>.?/"
let numeric = matches "0123456789"
let alphanumeric = matches "abcdefghijklmopqrstuvwxyz_'ABCDEFGHIJKLMNOPQRSTUVWXYZ"
F#倾向于使用轻量级而非冗长的语法编写,因此您通常不需要使用in
,begin
和end
关键字。有关差异的详细信息,请参阅:https://msdn.microsoft.com/en-us/library/dd233199.aspx。
就个人而言,我可能会将所有这些string -> bool
函数重构为活动模式,例如:
let (|Alphanumeric|_|) str =
match matches "abcdefghijklmopqrstuvwxyz_'ABCDEFGHIJKLMNOPQRSTUVWXYZ" str with
|true -> Some str
|false -> None
let (|Symbolic|_|) str =
match matches "~'!@#$%^&*-+=|\\:;<>.?/" str with
|true -> Some str
|false -> None
然后你可以模式匹配,例如:
match c with
|Alphanumeric _ -> // alphanumeric case
|Symbolic _ -> // symbolic case
|_ -> // other cases