我正在尝试制作一个处理订单的酒吧模拟器。发送到代理的消息属于此类型。
type DTGCafeMessage =
| OrderDrink of Drink * float
| LeaveAComment of string
代理是下面实现的bar类。
type Bar() =
let dtgCafeAgent =
MailboxProcessor.Start
(fun inbox ->
let rec messageLoop () =
async {
let! msg = inbox.Receive()
match msg with
| OrderDrink (drink, amount) ->
let drinkPrice : float = getPrice drink
let mutable totalPrice = ((drinkPrice: float) * (amount: float))
if drink.type' = Coffee then
totalPrice <- dgtVAT totalPrice VAT
printfn
"Please pay DKK%d for your %d %A %A drinks. %s!"
(Convert.ToInt32(totalPrice))
(Convert.ToInt32(amount))
(string drink.type')
(string drink.size)
"Thanks!"
| LeaveAComment (comment) -> printf "Comment: %A" comment
return! messageLoop ()
}
messageLoop ())
member this.Order msg = dtgCafeAgent.Post msg
当我把信息发送给代理时,它正在以一种非常混乱的方式打印东西。
let bar = Bar()
let testDrink = { type' = Coffee; size = Small }
bar.Order(OrderDrink({ type' = Coffee; size = Small }, 2.0))
let orderDrinks =
[ (OrderDrink({ type' = Coffee; size = Small }, 1.0))
(OrderDrink({ type' = Coffee; size = Medium }, 2.0))
(OrderDrink({ type' = Juice; size = Small }, 3.0))
(OrderDrink({ type' = Soda; size = Medium }, 4.0))
(OrderDrink({ type' = Milk; size = Large }, 5.0)) ]
orderDrinks |> List.map (fun o -> bar.Order o)
// output
> orderDrinks |> List.map (fun o -> bar.Order o);;
valPlease pay DKK24 for your 1 "Coffee" "Small" drinks. Thanks!!
it Please pay DKK72 for your 2 "Coffee" :"Medium" drinks. Thanks!!
unitPlease pay DKK 45 for your 3 list"Juice" "Small" drinks. Thanks!!
=Please pay DKK51 for your 4 "Soda" "Medium" drinks. Thanks!!
[()Please pay DKK;125 for your 5 "Milk" "Large" drinks. Thanks!!
(); (); (); ()]
正如我所看到的,它应该打印代码中所写的每一条语句。
Fsi正在评估您的表达式。自从酒吧。Order((返回单位,表达式的结果为[((;((。所以Fsi想打印类似的东西
val it : unit list = [(); (); (); (); ()]
同时,邮箱处理器在另一个线程上处理其队列,在打印消息的同时打印消息。这两个线程都在向同一输出发送文本,即它们相互踩在一起。
只需进行
orderDrinks |> List.iter bar.Order
如果你只是想打印结果。
List.map会转换输出,但输出的类型是例如((,并得到您看到的混乱结果。
编辑:您还需要启动fsi-quiet,这样它就不会打印变量评估,例如fsi-quiet
否则,行为是正确的,因为它显示了邮箱处理器如何开始执行任务,并在完成之前将控制权移交给调用者。因此,调用方fsi开始打印val-it:unit((。在邮箱处理器工作的同时。两个进程同时向控制台进行写入,从而产生混乱的输出。
Still List.Iter用于执行没有输出的函数,例如有unit((输出;而不是每个列表项返回一个单元((。