Object F#:我不能在do子句中返回单位,并且仍然有副作用

Object F#:我不能在do子句中返回单位,并且仍然有副作用,object,f#,initialization,unit-type,Object,F#,Initialization,Unit Type,我正在编写一个简单的ini文件解析器,在“do”子句中初始化对象时遇到了一个小问题。它想让我返回一个单位,但如果我试图通过管道输入一个“忽略”或直接返回“()”的话,我无法让空白函数产生副作用 这段代码作为一个单独的函数工作,因为我可以忽略结果 #light module Utilities.Config open System open System.IO open System.Text.RegularExpressions open System.Collections.Generic

我正在编写一个简单的ini文件解析器,在“do”子句中初始化对象时遇到了一个小问题。它想让我返回一个单位,但如果我试图通过管道输入一个“忽略”或直接返回“()”的话,我无法让空白函数产生副作用

这段代码作为一个单独的函数工作,因为我可以忽略结果

#light

module Utilities.Config

open System
open System.IO
open System.Text.RegularExpressions
open System.Collections.Generic

type Config(?fileName : string) =
    let fileName = defaultArg fileName @"C:\path\myConfigs.ini"

    static let defaultSettings =
        dict[ "Setting1", "1";
              "Setting2", "2";
              "Debug",    "0";
              "State",    "Disarray";]

    let settingRegex = new Regex(@"\s*(?<key>([^;#=]*[^;#= ]))\s*=\s*(?<value>([^;#]*[^;# ]))")
    let fileSettings = new Dictionary<string, string>()
    let addFileSetting (groups : GroupCollection) =
        fileSettings.Add(groups.Item("key").Value, groups.Item("value").Value)

    do  File.ReadAllLines(fileName)
        |> Seq.map(fun line -> settingRegex.Match(line))
        |> Seq.filter(fun mtch -> mtch.Success)
        |> Seq.map(fun mtch -> addFileSetting(mtch.Groups) // Does not have the correct return type
        //|> ignore //#1 Does not init the dictionary
        //()        //#2 Does not init the dictionary

    //The extra step will work
    member c.ReadFile =
        File.ReadAllLines(fileName)
        |> Seq.map(fun line -> settingRegex.Match(line))
        |> Seq.filter(fun mtch -> mtch.Success)
        |> Seq.map(fun mtch -> addFileSetting(mtch.Groups))
#灯
模块实用程序.Config
开放系统
开放系统
打开System.Text.RegularExpressions
open System.Collections.Generic
类型配置(?文件名:字符串)=
让fileName=defaultArg fileName@“C:\path\myconfig.ini”
静态let默认设置=
dict[“设置1”,“1”;
“设置2”、“设置2”;
“调试”、“0”;
“状态”、“混乱”;]
设settingRegex=new Regex(@“\s*(?([^;#=]*[^;#=]))\s*=\s*(?([^;#]*[^;#]]))
让fileSettings=newdictionary()
让addFileSetting(组:GroupCollection)=
添加(groups.Item(“key”).Value,groups.Item(“Value”).Value)
do File.ReadAllLines(文件名)
|>序列图(有趣的线条->设置正则表达式匹配(线条))
|>序列过滤器(趣味mtch->mtch.Success)
|>Seq.map(fun mtch->addfileset(mtch.Groups)//没有正确的返回类型
//|>ignore/#1不初始化字典
//()/#2不在字典中
//额外的步骤会奏效
成员c.ReadFile=
File.ReadAllLines(文件名)
|>序列图(有趣的线条->设置正则表达式匹配(线条))
|>序列过滤器(趣味mtch->mtch.Success)
|>Seq.map(有趣的mtch->addfileset(mtch.Groups))
使用
Seq.iter
(对每个元素执行操作-返回
单元
)而不是
Seq.map
(转换元素)

代码与
ignore
不起作用,因为
Seq
是惰性计算的,当您忽略结果时,根本不需要运行任何代码。

使用
Seq.iter
(对每个元素执行一个操作-返回
单元
),而不是
Seq.map
(转换元素)

该代码不适用于
ignore
,因为
Seq
是惰性计算的,当您忽略结果时,根本不需要运行任何代码