gpt4 book ai didi

f# - F# 中的其他构造函数

转载 作者:行者123 更新时间:2023-12-04 02:38:52 26 4
gpt4 key购买 nike

我正在尝试在 F# 中创建一个额外的构造函数,它执行一些额外的工作(即读取一个基本的 csv 文件),如下所示:

type Sheet () =
let rows = new ResizeArray<ResizeArray<String>>()
let mutable width = 0

new(fileName) as this =
Sheet()
then
let lines = System.IO.File.ReadLines fileName
for line in lines do
let cells = line.Split ','
rows.Add(new ResizeArray<String> (cells)) //line 16
if cells.Length > width then width <- cells.Length

但我收到以下错误:
Error   1   The namespace or module 'rows' is not defined   C:\Users\ga1009\Documents\PhD\cpp\pmi\fsharp\pmi\Csv.fs 16
Error 2 The value or constructor 'width' is not defined C:\Users\ga1009\Documents\PhD\cpp\pmi\fsharp\pmi\Csv.fs 17
Error 3 The value or constructor 'width' is not defined C:\Users\ga1009\Documents\PhD\cpp\pmi\fsharp\pmi\Csv.fs 17

我究竟做错了什么?

最佳答案

正如 Daniel 指出的那样,F# 设计是你有一个主构造函数,它通常接受类所需的所有参数并执行初始化。其他构造函数可以为参数提供默认值,也可以根据其他信息计算它们。

在你的情况下,我认为最好的设计是通过 rows作为构造函数参数。然后您可以添加两个额外的构造函数(一个加载文件,另一个提供空列表)。

这使代码更简单一些,因为您不必检查是否提供了参数(如 Daniel 的版本)。我还做了一些其他的简化(即在功能上计算 width 并使用序列推导式 - 如果 Sheet 不修改数据,您也可以避免使用 ResizeArray ):

type Sheet private (rows) =  
// The main constructor is 'private' and so users do not see it,
// it takes columns and calculates the maximal column length
let width = rows |> Seq.map Seq.length |> Seq.fold max 0

// The default constructor calls the main one with empty ResizeArray
new() = Sheet(ResizeArray<_>())

// An alternative constructor loads data from the file
new(fileName:string) =
let lines = System.IO.File.ReadLines fileName
Sheet(ResizeArray<_> [ for line in lines -> ResizeArray<_> (line.Split ',') ])

关于f# - F# 中的其他构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12056573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com