我正在處理一個字符串列表,你可以將它們想象成一本書的行。 當一條線是空的時,它必須被丟棄。當它是標題時,它被「保存」爲當前標題。每個「正常」行必須生成一個包含文本和當前標題的對象。 最後你有一系列的行,每行都有相應的標題。處理中間狀態的列表
例:
- Chapter 1
Lorem ipsum dolor sit amet
consectetur adipisicing elit
- Chapter 2
sed do eiusmod tempor
incididunt u
第一行是一個標題,第二線必須被丟棄,則兩條線保持爲段落,每個用「第1章」的標題。等等。你結束了類似的集合:
{"Lorem ipsum...", "Chapter 1"},
{"consectetur...", "Chapter 1"},
{"sed do...", "Chapter 2"},
{"incididunt ...", "Chater 2"}
我知道標題/段模型不使100%的感覺,但我簡化模型來說明這個問題。
這是我的迭代求解:
let parseText allLines =
let mutable currentTitle = String.Empty
seq {
for line in allLines do
match parseLine line with
| Empty -> 0 |> ignore
| Title caption ->
currentTitle <- caption
| Body text ->
yield new Paragraph(currentTitle, text)
}
第一個問題是我不得不丟棄空行,我這樣做是與0 |> ignore
但它看起來很對我不好。什麼是適當的做到這一點(沒有預過濾列表)?
此功能的尾遞歸版本很簡單:
let rec parseText allLines currentTitle paragraphs =
match allLines with
| [] -> paragraphs
| head :: tail ->
match head with
| Empty -> parseText tail currentTitle paragraphs
| Title caption -> parseText tail caption paragraphs
| Body text -> parseText tail currentTitle (new Paragraph(currentTitle, text) :: tail)
的問題(S):
- 有兩個版本 (風格/性能之間的顯著差異/等等)?
- 有沒有更好的方法來解決這個 問題?是否可以用一個List.map來完成它?
現在這是非常好的! –