F #: لا أستطيع إرجاع وحدة في جملة Do ولا يزال لها آثار جانبية
-
19-09-2019 - |
سؤال
أنا أكتب محلل ملف 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))
المحلول
يستخدم Seq.iter
(تنفيذ إجراء لكل عنصر - العودة unit
) بدلا من Seq.map
(تحويل العناصر).
الكود لا يعمل مع ignore
لأن Seq
يتم تقييمها بشكل مكتمل وعندما تجاهل النتيجة، ليست هناك حاجة لتشغيل أي رمز على الإطلاق. اقرأ هذه المقالة
لا تنتمي إلى StackOverflow