从F#中获取元组集中的元素

Feo*_*akt 3 f# tuples set

我想在前两个值的集合中找到元组并返回元组的第三个值(如果没有找到则返回None).我喜欢这样的事情:

type Point = (int * int * int)
type Path = Set<Point>

let f (x:int) (y:int) (p:Path) : int Option =
    if Set.exists ((=) (x, y, _z)) p
    then Some _z
    else None

let p:Path = Set.ofList [ (0, 1, 100); (1, 1, 500); (1, 2, 50); ]

f 1 2 p
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为显然,表达式中不允许模式匹配.什么是正确的方法?谢谢.

hve*_*ter 5

您可以将该集转换为列表并使用List.tryFind

let f (x:int) (y:int) (p:Path) : int Option =
    Set.toList p
    |> List.tryFind (fun (px, py, _) -> x = px && y = py)
    |> Option.map (fun (_, _, pz) -> pz)
Run Code Online (Sandbox Code Playgroud)


The*_*Fox 5

迭代hvester的回答:

let f (x:int) (y:int) (p:Path) : int Option =
    p |> Seq.tryPick (function
                      | x', y', z' when x = x' && y = y' -> Some z'
                      | _ -> None)
Run Code Online (Sandbox Code Playgroud)

tryPick 基本上只需一步即可查找和映射.