types - f# Narrow discriminated union in previous pattern matching guard(Control Flow Based Type Analysis)

标签 types f#

如果类型在之前的守卫中被缩小,F# 会缩小类型吗?

type FirstOption = bool option
type SecondOption = bool option

let foo first second =
     match first with
     | None -> false
     | Some value when second.IsSome ->
          // second is still Option<bool>
          sencond // x this doesn't fly.
     | Some value -> false

在这些情况下,我一直在使用 Optopn.map/map2/map3,但想知道我是否做错了什么。

对于 TypeScript,他们有基于控制流的分析:https://github.com/microsoft/TypeScript/issues/2388

最佳答案

您可以对两个选项进行模式匹配(很好地匹配两个选项的元组)

转换你的例子:

let foo first second = 
  match (first, second) with
  | (None, _) -> false
  | (Some _, Some s) -> s
  | (Some x, None) -> false

可以简化为:

let foo first second =
   match (first, second) with
   | (Some _, Some s) -> s
   | _ -> false

关于types - f# Narrow discriminated union in previous pattern matching guard(Control Flow Based Type Analysis),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63231237/

相关文章:

f# - v3.1中命名联合字段的编译形式

swift - 在 Swift 浮点值和 "X": Polloquin Exercise Notation 中创建类型

python - 结合python中的几种结构类型

haskell - 与 TypeApplications 一起使用时,AllowAmbigouslyTypes 有多危险?

f# - 使用寓言在 F# 中解析 Thenable<'> 的语法是什么?

oop - 纯函数式编程上下文中的面向对象编程?

exception - 试图组合一些断言函数,但我无法尝试工作

list - 为什么 F# 列表范围比 for 循环慢这么多?

c++ - 不简单,从 char[8] 转换 long long

c# - 如何获取描述基本类型数组的类型?