考虑以下代码:
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
产生以下错误:init.fsx(6,30): error FS0001: This expression was expected to have type int but here has type 'a option
MSDN状态:
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# 选项类型,否则代码会编译。而且我不明白为什么,当我悬停在
?bo
上时在 fn3
工具提示说 val bo: int option
但外界只期待 int
.我希望有一种不接受任何东西、int、Some int 和 None 的行为。最后一点,我不明白为什么 fn2
有效但 fn4
才不是。谢谢澄清
最佳答案
我必须重新考虑正确答案。基于这个问题(和答案):
Propagating optional arguments
看来正确答案如下:
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 !
关于f# - 使用 F# 的可选参数和选项类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6353897/