以下是一个例子:
type Events =
| A of AData
| B of BData
| C of CData
我有一个列表:
let events : Events list = ...
我需要按事件类型建立一个列表。目前我是这样做的:
let listA =
events
|> List.map (fun x ->
match x with
| A a -> Some a
| _ -> None
)
|> List.choose id
然后,对于每种类型都进行重复...
我还认为我可以做类似于:
let rec split events a b c =
match events with
| [] -> (a |> List.rev, b |> List.rev, c |> List.rev)
| h :: t ->
let a, b, c =
match h with
| A x -> x::a, b, c
| B x -> a, x::b, c
| C x -> a, b, x::c
split t a b c
有没有更优雅的方式来解决这个问题?
这里处理了许多数据,因此速度很重要。
type Events
可能不太适合当前的任务。当然,这取决于可以承受的重构规模。 - kkm