我是f#的新手,我試圖編寫一個程序,該程序應該通過給定目錄中的所有文件併爲每個類型爲「.txt」的文件添加一個id號碼+「完成」到文件。如何在沒有「printf」的情況下調用Seq.whatever中的函數?
我的程序:
//const:
[<Literal>]
let notImportantString= "blahBlah"
let mutable COUNT = 1.0
//funcs:
//addNumber --> add the sequence number COUNT to each file.
let addNumber (file : string) =
let mutable str = File.ReadAllText(file)
printfn "%s" str//just for check
let num = COUNT.ToString()
let str4 = str + " " + num + "\n\n\n DONE"
COUNT <- COUNT + 1.0
let str2 = File.WriteAllText(file,str4)
file
//matchFunc --> check if is ".txt"
let matchFunc (file : string) =
file.Contains(".txt")
//allFiles --> go through all files of a given dir
let allFiles dir =
seq
{ for file in Directory.GetFiles(dir) do
yield file
}
////////////////////////////
let dir = "D:\FSharpTesting"
let a = allFiles dir
|> Seq.filter(matchFunc)
|> Seq.map(addNumber)
printfn "%A" a
我的問題:
TF我不寫的最後一行(printfn 「%A」 一個)的文件將不會改變(如果我不寫這條線。它的工作原理和更改文件) 當我使用調試器我發現它並沒有真正計算'a'的值,當它到達行時,如果「let a = ......」它繼續到printfn並且比它在「看到」'a'時返回並計算'a'的答案時更爲重要。 爲什麼它,我怎麼能「打開」功能,而不打印?
也有人可以告訴我爲什麼我必須添加文件作爲函數「addNumber」的返回類型? (我加了這一點,因爲它是如何工作的,但我真的不明白爲什麼....)
最後question- 如果我的[]定義 線後寫COUNT變量正確它提供了一個錯誤,並說一個常量不能「可變」,但如果添加(這是爲什麼我這樣做)另一行之前(如字符串)它「忘記」了錯誤和工作。 爲什麼?如果你真的不能有一個可變的常量,我該如何做一個靜態變量?
好的,我明白了! 非常感謝每一個! – nati 2013-02-19 19:56:50