我需要從套接字解析輸入流。 數據是從Telnet客戶端發送的,因此我想通過查找流中的第一個'\r'
字符來處理傳入的字符串,然後在返回字符前選擇字節,最後處理任何字符。解析Ascii字符的傳入TCP流,處理退格符char
在這裏處理'\b'
位的慣用方法是什麼? 我目前正在使用一個可變堆棧並將字符推送到它上面,如果有退格,我彈出最後一個字符。 然後只需將結果轉換爲字符串。
但我覺得可能有一些很好的方式來做到這一點與模式匹配和尾遞歸。那麼,這怎麼可以做到F#的方式呢?
let receiveInput (inputBuffer:StringBuilder) (received:Tcp.Received)=
let text = Encoding.ASCII.GetString(received.Data.ToArray());
inputBuffer.Append(text) |> ignore
let all = inputBuffer.ToString()
match all.IndexOf('\r') with
| enter when enter >= 0 ->
let textToProcess = all.Substring(0,enter)
inputBuffer.Remove(0,enter+2) |> ignore
//this is the part I'm wondering about
let stack = new Stack<char>()
for c in textToProcess do
if c = '\b' then stack.Pop() |> ignore
else stack.Push c
let input = new System.String(stack |> Seq.rev |> Seq.toArray)
Some(input)
| _ ->
None
啊是的,它應該摺疊不減少,沒有意識到在f# –
@RyanWGough'reduce'類似於'fold',但它輸入爲空時崩潰。 –
謝謝,真棒,這正是我正在尋找的。 –