【问题标题】:How to find a specific discriminated union from the same type,in a sequence,and then return that specific discriminated union if it exists如何从相同类型的序列中找到特定的可区分联合,然后返回该特定的可区分联合(如果存在)
【发布时间】:2019-04-23 03:22:06
【问题描述】:

我想检查一个序列中是否存在特定可区分联合的元素,如果存在,我想返回该特定元素。

 type Shape = 
   | Rectangle of float * float 
   | Circle 
   | Prism 
 let rectangle1 = Rectangle(5.0,1.2)
 let rectangle2 = Rectangle(2.0,1.4)
 let test = [Circle;Prism;rectangle2;rectangle1]

 let getShape shape = 
   match shape with
   | Rectangle(a,b) -> Some(a)
   | _ -> None


let x = 
  if test |> List.exists (fun shape -> (getShape shape) = Some(1.0)) then 
      ???
  elif test|> List.exists (fun shapre -> shape = Circle) then 
      Circle 
  else 
      Prism

对于上面的代码,我希望能够检查是否有一个矩形的形状,元组的第一个元素是 1.0

此检查有效:test |> List.exists (fun shape -> (getShape shape) = Some(1.0))

但是,我不知道如何返回从该表达式中找到的“形状”。

我希望它用于序列,但上面的示例使用 List。我想它也适用于序列。

【问题讨论】:

    标签: f#


    【解决方案1】:

    List.tryFind 听起来像你的need。也适用于Seq

    在你的情况下,我相信它看起来像这样:

    let x = test |> List.tryFind (fun shape -> (getShape shape) = Some(1.0))

    x 应该是Shape 类型之后,您仍然需要进行模式匹配才能将其作为Rectangle 进行操作。

    Rectangle 这里不是一个类型(尽管它可能在编译后表示为一个),而是一个值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-21
      • 2018-11-24
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      相关资源
      最近更新 更多