使用F#选项后
键入一段时间,我认识到,它可用于处理特殊情况。我可以使用选项
或异常
在下面的例子:
After using F# option
type for a while, I realize that it could be used for handling exceptional cases. I can use either option
or Exception
in the following examples:
查找
从列表功能/磁盘阵列/ SEQ模块筹集 KeyNotFoundException
在罕见的情况下,而相应的 tryFind
同行返回无
在这些情况下。
当我回溯(解决N皇后,数独等),每当一个分支无解,我可以抛出一个异常,后来将其接住或返回无以匹配值原路返回。这些案件发生往往直到我们找到一个解决方案。
The find
functions from List/Array/Seq modules raise KeyNotFoundException
in uncommon cases, while corresponding tryFind
counterparts return None
in those situations.
When I do backtracking (in solving N-queens, Sudoku, etc), whenever a branch has no solution, I can either raise an exception and catch it later or return None to match that value to backtrack. Those cases occur quite often until we find a solution.
我的IM pression是选项
是一种功能更强大的方法,而异常
是比较常用的在.NET平台上。
My impression is option
is a more functional approach, while Exception
is more commonly-used in the .NET platform.
什么是可用性,性能等方面中的异常处理选项
和异常
之间的差异?其中使用的技术的情况下比使用其他更好的?的
What are differences between option
and Exception
in exception handling in terms of usability, performance, etc? In which cases using a technique is better than using the other?
在CLR做抛接异常非常昂贵的操作。仅仅因为这个原因,你应该preFER结构,如选项报告预期故障。如果故障是真正的无与伦比的,几乎不可恢复,继续抛出异常。但是当你注意的,像搜索过程回溯是平常,你会发现你的性能会受到很大的,如果你有例外的贯彻落实。
The CLR makes the operation of throwing and catching an exception extremely expensive. For this reason alone, you should prefer constructs like Option for reporting expected failures. If the failure is truly exceptional and nearly unrecoverable, go ahead and throw an exception. But as you note, things like backtracking during a search are unexceptional, and you will find your performance suffers greatly if you implement them with exceptions.
由于这是CLR的一个属性,它并没有真正不管你是在F#与否。我的理解是,其他运行时为ML-样的语言,如ocaml的,不具有这个特点,因此可以使用异常更频繁地控制流量。
Because this is a property of the CLR, it doesn't really matter whether you are in F# or not. My understanding is that other runtimes for ML-like languages, e.g. ocaml, do not have this characteristic, and so may use exceptions more often for control flow.