代码之家  ›  专栏  ›  技术社区  ›  Dylan

F#从列表中选择0或1的区分联合

  •  1
  • Dylan  · 技术社区  · 15 年前

    type thing = { One:int; Two:int; Three:int}
    
    type data = 
        | Alpha of int
        | Bravo of thing
        | Charlie of string
        | Delta of Object
    
    //generate some data
    let listData = [
                    Alpha(1);
                    Alpha(2);
                    Bravo( { One = 1; Two = 2; Three = 3 } );
                    Charlie("hello");
                    Delta("hello again")]
    
    //find the 0 or 1 instances of bravo and return the data as a thing
    let result =    listData 
                    |> List.map( function | Bravo b -> Some(b) | _ -> None)
                    |> List.filter( fun op -> op.IsSome)
                    |> (function | [] -> None | h::t -> Some(h.Value))
    

    谢谢

    2 回复  |  直到 15 年前
        1
  •  2
  •   kvb    15 年前

    怎么样

    let result =
      listData
      |> List.tryPick (function | Bravo b -> Some b | _ -> None)
    
        2
  •  0
  •   dahlbyk    15 年前

    let result = listData
                 |> List.tryFind (function | Bravo b -> true | _ -> false)
    
    推荐文章