我似乎无法在F#中使用以下功能。我已附上以下代码。
第一期:在其所在的行
Select(g => new {Cluster
显示的错误是'意外符号'{'in expression'。
第二个问题:在进行条件检查的行
If (EmptyCluster(_normalisedDataToCluster) = true) then return false
抱怨错误,'此构造只能在计算表达式中使用。要从普通函数返回值,只需编写表达式而不返回'。
let EmptyCluster(data : List<DataPointClass>) =
let emptyCluster = data.GroupBy(s => s.Cluster)
.OrderBy(s => s.Key)
.Select(g => new {Cluster = g.Key, Count = g.Count})
//complains about the curly braces inside the Select expression above
for item in emptyCluster do
if (item.Count = 0) then
return true
return false
let UpdateDataPointMeans() =
if (EmptyCluster(_normalisedDataToCluster) = true) then
return false //complains about this return statement
let mutable groupToComputeMeans = _normalisedDataToCluster
.GroupBy(s => s.Cluster).OrderBy(s => s.Key)
let mutable clusterIndex = 0
let mutable height = 0.0
let mutable weight = 0.0
for item in groupToComputeMeans do
for value in item do
height <- height + value.Height
weight <- weight + value.Weight
_clusters.[clusterIndex].Height <- height / Convert.ToDouble item.Count
_clusters.[clusterIndex].Weight <- weight / Convert.ToDouble item.Count
clusterIndex <- clusterIndex + 1
height <- 0.0
weight <- 0.0
true
type DataPointClass(height : double, weight : double) = class
let mutable _height = height
let mutable _weight = weight
let mutable cluster = 0
member self.Height with get () = _height and set (value) = _height <- value
member self.Weight with get () = _weight and set (value) = _weight <- value
member self.Cluster with get () = cluster and set (value) = cluster <- value
new() =
DataPointClass(-1.0, -1.0)
then
printfn "Error initialising"
end
答案 0 :(得分:3)
所以你并没有真正编写F#代码,你真的应该学习如何以这种方式编写代码。以Linq为例似乎没有多大意义......您还应该考虑制作它,以便您的代码示例实际上可以编译,所以我们不必猜测例如什么类型是DataPointClass
。
那说是为了解决你的具体问题:
第一期 :
如果您查看constructor documentation,则会看到如果您有自定义类型,则会使用关键字new
。像这样:
type MyClass(clus, ct) =
let mutable cluster = clus
let mutable count = ct
member this.Cluster with get() = cluster
member this.Count with get() = count
new() = MyClass("", 0)
let test = new MyClass()
但是,您似乎在这里使用了记录类型,这意味着您根本不需要新的关键字......像{Cluster = g.Key; Count = g.Count}
这样的内容会自动创建相应MyClass
的新类1}}。
第二期 :
再次查看keyword guide,我们发现关键字return
仅用于 async 工作流程:Used to indicate a value to provide as the result of a computation expression.
它不用于表示返回一个函数的价值。要从函数返回,您根本不需要使用任何关键字。这是一个简单的例子:
let multiplyByTwo x = x*2
请注意我们根本不必使用退货。编译器会自动知道。