我试图在F#中传递参考信息。在C#中,使用ref和out关键字非常容易,但在F#中,它似乎没有那么简单。我刚读到:http://davefancher.com/2014/03/24/passing-arguments-by-reference-in-f/,它建议使用引用单元格。(我想这意味着在C#中没有模拟out关键字,在这里您不需要初始化一个变量就可以传递它。)
但是无论如何,我想知道这是否是在F#中传递引用的最佳/唯一方式,在函数式语言中这是否是一个好主意。
编辑:
我之所以感兴趣,是因为我刚刚意识到异常正在减缓我的代码。我正在进行一场消灭他们的运动。基本上,我的计划是:假设一个函数返回一个double,或者在出现错误时抛出一个异常。相反,我将通过引用传递一个double和一个ErrorCode类型作为位掩码,然后将值和错误向下传递。我猜我得让所有这些变量都变了。
发布于 2015-05-11 09:04:55
你的问题有几个部分,我将试着回答:
- Yes, Reference Cells (or ref cells) are the idiomatic way to pass mutable data into a function
- C# usually uses `out` parameters to signify additional return values. The idomatic way to do that in F# is with tuples. For example the C# function `int TryParse(string s, out bool succeeded)` is simply `TryParse(s : string) -> (int, bool)`
- This is certainly not what I would consider to be normal, idiomatic F# code. The way I would represent this would be with a Discriminated Union representing the possible results:
type MyFunctionResult =
| Success of double
| ErrorCase1
| ErrorCase2 of AddditionalDataType
等
如果您有许多使用这种样式的函数,那么它就是 function。
发布于 2015-05-11 08:40:37
您可以使用&
而不是C#的ref
,但是以&
作为前缀的变量必须是可变的。
open System.Collections.Generic
let dic = new Dictionary<string, string>()
dic.Add("key", "myvalue")
let mutable v = "" // v is mutable
let success = dic.TryGetValue("key", &v);
System.Console.WriteLine(v)
let succ, value = dic.TryGetValue("key") // this is what Mark Seemann says is the comment, a shortcut for C#'s `Try...(.., out ...)` is using tuples in F#
发布于 2015-05-11 08:34:36
让我描述一下OCaml所做的事情,因为我不知道F#,而且有人可以确认F#非常相似,因此我的答案也适用。
在函数式编程语言(如OCaml或F# )中,默认情况下数据是不可变的。也就是说,您需要在事物发生变化之前声明它们是可变的,实际上,可变的数据结构不像不可变的数据结构那么常见(但并不少见)。
现在,由于数据在默认情况下是不可变的,因此如何传递参数并不重要,因为它们无论如何都不会被更改。在这种情况下,通过值传递简单的数据类型是有意义的,而其他的类型则通过引用传递到寄存器中。
当然,可变数据类型是通过引用传递的,否则就没有什么价值了。
也许你可以给我们举个例子来说明你想做什么。您是传递可变的还是不变的数据?
https://stackoverflow.com/questions/30172904
复制