模式匹配不调用 F# 中的函数
Pattern matching does not call function in F#
open System
[<EntryPoint>]
let main argv =
match argv with
| [| firstArg |] -> printfn "Your first arg is %s", firstArg
| [| |] -> failwith "You didn't pass an argument"
| _ -> failwith "You did something unusual"
0 // return an integer exit code
我写这个是为了处理我的 F# 控制台应用程序的第一个参数。如果我没有传递参数,它就会失败,并出现异常 "You didn't pass an argument"。如果我至少传递了两个参数,它会失败并出现异常 "You did something unusual"。但是,当我恰好通过一个参数时,它什么也没说。为什么 printfn 在这里不起作用?
这里没有打印任何东西的原因是你在 printf 之后添加了一个额外的逗号。这意味着签名是一个 string -> unit
函数和字符串元组。如果您删除逗号,它将起作用。
一个可行的解决方案是
[<EntryPoint>]
let main argv =
match argv with
| [| firstArg |] -> printfn "Your first arg is %s" firstArg
| [| |] -> failwith "You didn't pass an argument"
| _ -> failwith "You did something unusual"
0 // return an integer exit code
您可能已经在 运行 之前看到编译器警告,它说 warning FS0020: The result of this expression has type '(string -> unit) * string' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'
open System
[<EntryPoint>]
let main argv =
match argv with
| [| firstArg |] -> printfn "Your first arg is %s", firstArg
| [| |] -> failwith "You didn't pass an argument"
| _ -> failwith "You did something unusual"
0 // return an integer exit code
我写这个是为了处理我的 F# 控制台应用程序的第一个参数。如果我没有传递参数,它就会失败,并出现异常 "You didn't pass an argument"。如果我至少传递了两个参数,它会失败并出现异常 "You did something unusual"。但是,当我恰好通过一个参数时,它什么也没说。为什么 printfn 在这里不起作用?
这里没有打印任何东西的原因是你在 printf 之后添加了一个额外的逗号。这意味着签名是一个 string -> unit
函数和字符串元组。如果您删除逗号,它将起作用。
一个可行的解决方案是
[<EntryPoint>]
let main argv =
match argv with
| [| firstArg |] -> printfn "Your first arg is %s" firstArg
| [| |] -> failwith "You didn't pass an argument"
| _ -> failwith "You did something unusual"
0 // return an integer exit code
您可能已经在 运行 之前看到编译器警告,它说 warning FS0020: The result of this expression has type '(string -> unit) * string' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'