1

请参阅最后的编辑。

为新手问题道歉。我正在尝试使用 Akka.net 在 F# 中实现一些东西。我对 F# 很陌生,我只使用过 Scala 的 Akka。基本上,我试图在 Scala 中实现一些非常简单的东西,即让 Actor 根据它接收到的消息类型做不同的事情。

我的代码在下面,它是对从 akka.net 网站上提取的 hello world 示例的轻微修改。我相信我的代码的第一个问题是它确实记录了模式匹配而不是类型模式匹配,但是我无法编写没有编译错误的类型匹配...任何帮助将不胜感激。谢谢你。

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,无法将字符串类型的对象转换为条目。

稍后编辑:我得到这个来处理这个变化,向下转换为对象:

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 有专门针对这种情况的东西吗?谢谢你。

4

1 回答 1

6

您应该使用有区别的联合(本示例中的命令类型)。然后你可以模式匹配它的选项。

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"] }

重要的是要说发送运算符具有以下签名:

#ICanTell -> obj -> unit

所以,如果你传递一个不同类型的消息,比如一个字符串,它会引发一个异常。

于 2015-04-18T04:21:57.797 回答