簡體   English   中英

F#匹配問題

[英]F# match question

這是我到目前為止:

type u = {str : string} //some type that has some property str (for simplicity, only one)
type du=
   | A of u
   | B of u // some discriminated union that carries u with it

然后,在某個地方,我有一個du序列,我正在做distinctBy和屬性做的不同是str。 我能想出的最好的是:

Seq.distinctBy (fun d -> match d with (A u|B u) -> u.str)

代碼有效,但我不喜歡在受歧視的聯盟的a和b上匹配,並希望用某些東西替換匹配。

問題是什么? :)

編輯:

在我的情況下,被區分的聯合的a和b將總是帶有相同的類型u,一個解決方案是擺脫du並添加它的字符串形式來輸入u並簡化整個混亂,但我想保留它現在的方式,因為我打算在a和b上做匹配...

作為du的財產,這次比賽怎么樣?

type u = {str : string}

type du =
    | A of u
    | B of u with
    member this.U =
        match this with
        (A u | B u) -> u

[A {str="hello"}; B {str="world"}; A {str="world"}]
|> Seq.distinctBy (fun x -> x.U.str)

//val it : seq<du> = seq [A {str = "hello";}; B {str = "world";}]

但是,我有一些想法可以更好地模擬你和你之間的關系,同時滿足你的“編輯”問題。 一種方法是簡單地使用元組:

type u = {str : string}

type du =
    | A
    | B

//focus on type u
[A, {str="hello"}; B, {str="world"}; A, {str="world"}]
|> Seq.distinctBy (fun (_,x) -> x.str)
//val it : seq<du * u> = seq [(A, {str = "hello";}); (B, {str = "world";})]

//focus on type du
let x = A, {str="hello"}
match x with
| A,_ -> "A"
| B,_ -> "B"
//val it : string = "A"

另一種方法是切換它並將du添加到u:

type du =
    | A
    | B

type u = { case : du; str : string}

//focus on type u
[{case=A; str="hello"}; {case=B; str="world"}; {case=A; str="world"}]
|> Seq.distinctBy (fun x -> x.str)
//val it : seq<u> = seq [{case = A;
//                        str = "hello";}; {case = B;
//                                          str = "world";}]

//focus on type du
let x = {case=A; str="hello"}
match x with
| {case=A} -> "A"
| {case=B} -> "B"
//val it : string = "A"

你真的不能像你描述的那樣簡化它,但你可以簡化它。 謝謝@Tomas Petricek

[ A { str = "A" }; B { str = "B" }; B { str = "B" } ] 
|> Seq.distinctBy (fun (A u | B u) -> u.str) 
|> Seq.toArray;;

產量

[| A {str = "A";}; B {str = "B";} |]

我對F#有點新鮮,但希望這會有所幫助。 在我看來,Active Patterns可能會讓您的生活更輕松,以減少您在模式匹配中輸入的內容。 而不是使用A a | B b你可以在它的位置使用活動模式AorB。

type u = { str : string }

type du = 
    | A of u
    | B of u

let (|AorB|) (v:du) =
    match v with
        | A a -> a
        | B b -> b

[A { str = "A" }; B { str = "B"}; A { str = "A"}]
    |> Seq.distinctBy (fun d -> 
                    match d with 
                        | AorB s -> s)
    |> Seq.iter (fun i -> match i with AorB c -> printfn "%s" c.str)

隨着斯蒂芬的加法,最后的表達可以這樣寫出來。

[A { str = "A" }; B { str = "B"}; A { str = "A"}]
|> Seq.distinctBy (|AorB|)
|> Seq.iter (fun i -> match i with AorB c -> printfn "%s" c.str)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM