我想在前两个值的集合中找到元组并返回元组的第三个值(如果没有找到则返回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
但这不起作用,因为显然,表达式中不允许使用模式匹配。什么是正确的方法?感谢。
答案 0 :(得分:5)
您可以将设置转换为列表并使用List.tryFind
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:colorPrimary">@color/colorPrimary</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:colorAccent">@color/colorPrimary</item>
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowContentTransitions">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:actionModeBackground">@color/colorPrimary</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:textColor">@color/myTextPrimaryColor</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
<item name="android:windowSharedElementExitTransition">@android:transition/move</item>
<item name="android:typeface">serif</item>
</style>
答案 1 :(得分:5)
迭代哈维特的回答:
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)
tryPick
基本上只需一步即可查找和映射。
答案 2 :(得分:2)
这是一个非常整洁的解决方案fold
let f x y p = Set.fold (function |None -> (fun (x_,y_,z) -> if x=x_ && y=y_ then Some z else None) |f ->fun _ -> f) None p
答案 3 :(得分:1)
这是你想要做的吗?
let f (x:int) (y:int) (p:Path) : int Option =
match p |> Set.filter (fun (x', y', _) -> x' = x && y' = y) |> Set.toList with
| [(_, _, z)] -> Some z
| [] -> None
| _ -> failwith "More than one point was found!"
示例:
> let p:Path = Set.ofList [ (0, 1, 100); (1, 1, 500); (1, 2, 50); ];;
val p : Path = set [(0, 1, 100); (1, 1, 500); (1, 2, 50)]
> f 1 2 p;;
val it : Option<int> = Some 50