请参阅最后编辑。
为新手的问题道歉。我试图在F#中使用Akka.net实现一些东西。我对F#非常陌生,我只使用过Scala的Akka。基本上,我试图在Scala中实现一些非常容易的东西,即让一个Actor根据它接收到的消息类型做不同的事情。
我的代码如下所示,这是对akka.net网站上删除的hello示例的轻微修改。我认为我的代码的第一个问题是它确实记录模式匹配而不是类型模式匹配,但是我无法在没有编译错误的情况下编写类型匹配匹配.任何帮助都将不胜感激。谢谢。
open Akka.FSharp
open Actors
open Akka
open Akka.Actor
type Entries = { Entries: List<string>}
let system = ActorSystem.Create "MySystem"
let feedBrowser = spawn system "feedBrowser" <| fun mailbox ->
let rec loop() = actor {
let! msg = mailbox.Receive()
match msg with
| { Entries = entries} -> printf "%A" entries
| _ -> printf "unmatched message %A" msg
return! loop()}
loop()
[<EntryPoint>]
let main argv =
feedBrowser <! "abc" // this should not blow up but it does
system.AwaitTermination()
0编辑:错误是运行时错误,System.InvalidCastException,无法将字符串类型的对象转换为条目。
稍后编辑:我让它处理此更改,向下转换为Object:
let feedBrowser = spawn system "feedBrowser" <| fun mailbox ->
let rec loop() = actor {
let! msg = mailbox.Receive()
let msgObj = msg :> Object
match msgObj with
| :? Entries as e -> printfn "matched message %A" e
| _ -> printf "unmatched message %A" msg
return! loop()}
loop()现在这两行工作正常。
feedBrowser <! "abc"
feedBrowser <! { Entries = ["a"; "b"] }第一个输出“不匹配的消息abc”,第二个输出条目。
在没有演员的情况下,有没有更好的方法来做这件事?akka.net有专门针对这种情况的东西吗?谢谢。
发布于 2015-04-18 04:21:57
您应该使用受歧视联盟 (本例中的命令类型)。然后,您可以模式匹配它的选项。
type Entries = { Entries: List<string>}
type Command =
| ListEntries of Entries
| OtherCommand of string
let stack() =
let system = ActorSystem.Create "MySystem"
let feedBrowser = spawn system "feedBrowser" <| fun mailbox ->
let rec loop() = actor {
let! msg = mailbox.Receive()
match msg with
| ListEntries { Entries = entries} -> printf "%A" entries
| OtherCommand s -> printf "%s" s
return! loop() }
loop()要发送您应该使用的信息:
feedBrowser <! OtherCommand "abc"
feedBrowser <! ListEntries { Entries = ["a"; "b"] }重要的是,send运算符具有以下签名:
#ICanTell -> obj -> unit因此,如果您传递一条具有不同类型的消息,比如字符串,它将引发异常。
https://stackoverflow.com/questions/29695429
复制相似问题