views:

126

answers:

1

I'm writing a simple ini file parser and I'm having a little problem with the initialization of the object in the "do" clause. It wants me to return a unit but i can't get the blankity function to do the side effects if I try to pipe into an "ignore" or if i return "()" directly.

This code works as a separate function because I can ignore the results.

#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))
+6  A: 

Use Seq.iter (executing an action for each element - returning unit) instead of Seq.map (transforming elements).

The code doesn't work with ignore because Seq's are evaluated lazily and when you ignore the result, there is no need to run any code at all. Read this article

Dario
+1 for helping me get Disciplined badge. :)
dahlbyk