f# - 使用 F# 的可选参数和选项类型

标签 f# types option optional-parameters

考虑以下代码:

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

虽然 fn1fn2工作正常,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/

相关文章:

linq - 是否有等效于 Enumerable.DefaultIfEmpty 的 F#?

f# - 与 anycpu 相比,针对 x64 有时会导致非常糟糕的性能

Scala案例类更新值

scala - 这种提升功能有名字吗?

.net - F# 编译器使死对象保持事件状态

f# - 在 F# 中缩放序列

java - List 和 LinkedList 之间的类型不兼容

java - 表达式的类型必须是数组类型,但它解析为字符串

go - 在 golang 中,是否可以从类型本身获取 reflect.Type,从名称作为字符串?

javascript - 多项选择,语法错误,无法识别的表达式:option [value = cc dd]