如何在F#中将两个(双精度选项)相乘 [英] How to multiply two (double option)s in F#

查看:117
本文介绍了如何在F#中将两个(双精度选项)相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码包含很多双选项类型;到目前为止,我已经非常成功地使用了Option.map函数,从而消除了必须在所有位置上某些"和无"进行匹配并将它们视为提升类型的需要,但是不确定在以下情况下该怎么做:

My code contains quite a few double option types; I've been using the Option.map function quite successfully so far to eliminate the need to have to match on Some and None all over the place and treat them as lifted types but am not sure what to do in the following scenario:

let multiplyTwoOptions option1 option2 : double option =
  if not (option1.IsSome && option2.IsSome) then None
  else Some (option1.Value * option2.Value)

我已经阅读,您不应以这种方式使用IsSome,但是替代方案(据我所知,对两个序列进行模式匹配似乎很费劲).我对F#还是很陌生,所以想知道是否还有一种惯用的方式?我觉得也许我需要一个Option.fold2之类的东西来同时作用于两个选项,但没有一个.

I've read that you shouldn't use IsSome in this way, but the alternative (as far as I can see, to pattern match on both sequentially, seems quite long winded). I'm still quite new to F# so wondered if there is a more idiomatic way? I feel like maybe I need something like an Option.fold2 to act on two options at once but there isn't one.

推荐答案

模式可以嵌套,这就是它们的强大功能.在这种情况下,您可以在元组上进行模式匹配:

Patterns can be nested, that's their great power. In this particular case, you can pattern match on the tuple:

match option1, option2 with
| Some x, Some y -> Some (x * y)
| _ -> None

这篇关于如何在F#中将两个(双精度选项)相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆