找出在模式匹配中使用 catch all 时这些类型不同的原因

问题描述 投票:0回答:1

我需要一些帮助来理解类型推断如何影响以下代码,这些代码来自于上一个问题(经过一些思考,我已将其简化为以下内容):

type 'a result =
  | Succ of 'a
  | Fail

let first f = function
  | Succ c -> let res = f c in Succ res
  | fail   -> fail

let second f = function
  | Succ c -> let res = f c in Succ res
  | Fail   -> Fail

我的问题是:为什么

f
中的
first
具有
('a -> 'a)
类型,而
f
中的
second
具有
('a -> 'b)
类型?

您可以在这里看到它。

ocaml
1个回答
1
投票
  • Fail
    Fail -> Fail
    中出现的两次
    second
    被视为两个不同的值,因此允许有不同的类型
    'a result
    'b result
    ,但是
  • fail
    fail -> fail
    中出现的两次
    first
    被视为相同的值,因此无法更改类型。

或者至少类型推断系统不允许它改变类型。我不确定这是否是这个特定解释器的规范或怪癖。

© www.soinside.com 2019 - 2024. All rights reserved.