使用F#的可选参数和选项类型 [英] Optional parameters and option types using F#
问题描述
考虑以下代码:
type Test () =
member o.fn1 (?bo) = 1
member o.fn2 (?bo) = o.fn1 bo
member o.fn3 (?bo) = 1 + bo.Value
member o.fn4 (?bo) = o.fn3 bo
fn1
和fn2
正常工作时,fn4
会产生以下错误:
While fn1
and fn2
work just fine, fn4
produces the following error:
init.fsx(6,30):错误FS0001:该表达式应具有int类型,但此处具有类型'a option
init.fsx(6,30): error FS0001: This expression was expected to have type int but here has type 'a option
MSDN 状态:
可选参数被解释为F#选项类型,因此您可以使用带有Some和None的匹配表达式,以常规方式查询选项类型.
Optional parameters are interpreted as the F# option type, so you can query them in the regular way that option types are queried, by using a match expression with Some and None.
对我来说,可选参数不会解释为F#选项类型,否则代码将被编译.此外,我不明白为什么,当我将鼠标悬停在fn3
中的?bo
上时,工具提示显示val bo: int option
,但从外面只能看到int
.我期望一种不接受任何内容的行为,即int,Some int和None.最后一点,我不明白为什么fn2
起作用但fn4
不能起作用.
To me, optional parameters are not interpreted as the F# option type otherwise the code would compile. Moreover I do not understand why, when I hover over ?bo
in fn3
the tooltip says val bo: int option
but from outside expects only int
. I would expect a behavior of accepting nothing, int, Some int and None. And as the last note, I do not understand why fn2
works but fn4
does not.
感谢您的澄清
推荐答案
我必须重新考虑正确的答案.基于这个问题(和答案):
I have to reconsider the correct answer. Based on this question (and answer):
它接缝正确的答案如下:
it seams that the correct answer is the following:
type Test () =
member o.fn1 (?bo) = 1
member o.fn2 (?bo) = o.fn1 bo
member o.fn3 (?bo) = 1 + bo.Value
member o.fn4 (?bo) = o.fn3 (?bo = bo)
这是一个简洁的功能,您可以在 desco 上找到答案.
It is a neat feature and credits for the answer go to desco!
这篇关于使用F#的可选参数和选项类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!