尝试使用F Sharps异步序列在单词列表中查找字谜(我知道有更好的算法来进行字谜查找,但试图了解异步序列)
从下面的'runTest'我怎么能 1.异步读取返回的collecion并输出到屏幕 阻止所有结果返回&显示最终计数/集合
open System
open System.ServiceModel
open System.Collections.Generic
open Microsoft.FSharp.Linq
open FSharp.Control
[<Literal>]
let testWord = "table"
let testWords = new List<string>()
testWords.Add("bleat")
testWords.Add("blate")
testWords.Add("junk")
let hasWord (word:string) =
let mutable res = true
let a = testWord.ToCharArray() |> Set.ofArray
let b = word.ToCharArray() |> Set.ofArray
let difference = Set.intersect a b
match difference.Count with
| 0 -> false
| _ -> true
let test2 (words:List<string>, (word:string)) : AsyncSeq<string> =
asyncSeq {
let res =
(words)
|> Seq.filter(fun x-> (hasWord(x)) )
|> AsyncSeq.ofSeq
yield! res
}
let runTest = test2(testWords,testWord)
|> //pull stuff from stream
|> // output to screen
|> ignore
()
答案 0 :(得分:4)
因为你有test2
函数返回asyncSeq。你的问题:
<强> 1。 async读取返回的collecion并输出到屏幕
如果您想要一些副作用代码(例如输出到屏幕),您可以使用AsyncSeq.iter
将功能应用于每个项目。 Iter返回Async<unit>
,然后您可以使用适当的异步方法(阻止/非阻塞)将其“踢掉”。
例如:
let processItem i =
// Do whatever side effecting code you want to do with an item
printfn "Item is '%s'" i
let runTestQ1 =
test2 (testWords, testWord)
|> AsyncSeq.iter processItem
|> Async.RunSynchronously
<强> 2。阻止所有结果返回&amp;显示最终计数/集合
如果您希望收集所有结果以便可以一起处理它们,那么您可以使用AsyncSeq.toBlockingSeq
将AsyncSeq转换为普通Seq,然后将其转换为列表以强制Seq进行评估。 / p>
例如:
let runTestQ2 =
let allResults =
test2 (testWords, testWord)
|> AsyncSeq.toBlockingSeq
|> Seq.toList
// Do whatever you would like with your list of results
printfn "Final list is '%A' with a count of %i" allResults (allResults.Length)