从F#函数多次退出 [英] Multiple Exits From F# Function
问题描述
我可以在C ++中轻松做到这一点(注意:我没有测试它的正确性-只是为了说明我正在尝试做的事情):
I could do this easily in C++ (note: I didn't test this for correctness--it's only to illustrate what I'm trying to do):
const int BadParam = -1;
const int Success = 0;
int MyFunc(int param)
{
if(param < 0)
{
return BadParam;
}
//normal processing
return Success;
}
但是我不知道如何在F#的早期退出例程.我想做的是在输入错误的情况下退出该功能,但如果输入正常,则继续操作.我是不是在缺少F#的某些基本属性,还是因为我只是在学习FP而以错误的方式解决问题? failwith 是我唯一的选择吗?
But I cannot figure out how to exit a routine early in F#. What I want to do is to exit the function on a bad input but continue if the input is ok. Am I missing some fundamental property of F# or am I approaching the problem in the wrong way since I'm just learning FP? Is a failwith my only option here?
这是我到目前为止所掌握的内容,并且可以正常编译:
This is what I've got so far and it compiles ok:
#light
module test1
(* Define how many arguments we're expecting *)
let maxArgs = 2;;
(* The indices of the various arguments on the command line *)
type ProgArguments =
| SearchString = 0
| FileSpec = 1;;
(* Various errorlevels which the app can return and what they indicate *)
type ProgReturn =
| Success = 0
| WrongNumberOfArgumentsPassed = 1;;
[<EntryPoint>]
let main (args:string[]) =
printfn "args.Length is %d" args.Length
let ProgExitCode = if args.Length <> maxArgs then
printfn "Two arguments must be passed"
int ProgReturn.WrongNumberOfArgumentsPassed
(* Want to exit "main" here but how? *)
else
int ProgReturn.Success
let searchstring, filespec = args.[int ProgArguments.SearchString],args.[int ProgArguments.FileSpec];
printfn "searchstring is %s" searchstring
printfn "filespec is %s" filespec
ProgExitCode;;
是否有FP处理这种情况的方法?
Is there an FP way of dealing with this sort of thing?
推荐答案
在我看来,匹配表达式是早期退出的F#类似物,用于指出错误条件并分别处理它们.对于您的示例,我会写:
In my opinion, match expressions are the F# analogue of early-exit for calling out erroneous conditions and handling them separately. For your example, I'd write:
[<EntryPoint>]
let main (args:string[]) =
printfn "args.Length is %d" args.Length
match args with
| [| searchstring; filespace |] ->
// much code here ...
int Success
| _ -> printfn "Two arguments must be passed"
int WrongNumberOfArgumentsPassed
这很好地分隔了错误情况.通常,如果需要从某事物的中间退出,请拆分函数,然后将错误情况放在match
中.在功能语言中,小函数的数量实际上没有限制.
This separates the error case nicely. In general, if you need to exit from the middle of something, split functions and then put the error case in a match
. There's really no limit to how small functions should be in a functional language.
顺便说一句,将区分联合用作整数常量集有点不可思议.如果您喜欢这种惯用语,请注意,在引用它们时不需要包括类型名称.
As an aside, your use of discriminated unions as sets of integer constants is a little weird. If you like that idiom, be aware that you don't need to include the type name when referring to them.
这篇关于从F#函数多次退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!