我在編寫結果類型和各種函數時遇到了問題,並遇到了我無法解釋的類型不匹配錯誤。下面是一個最小的例子:結果類型中的類型不匹配錯誤
type ('a, 'b) result =
| Success of 'a
| Failure of 'b list
let apply fr xr =
match fr, xr with
| Success f, Success x -> Success (f x)
| Failure _, Success _ -> fr
| Success _, Failure _ -> xr
| Failure a, Failure b -> Failure (List.concat [a; b])
編譯此代碼產生以下錯誤:如果您更改按照以下申請功能
init.fsx(8,31): error FS0001: Type mismatch. Expecting a
('a,'b) result
but given a
(('c -> 'a),'d) result
The resulting type would be infinite when unifying ''a' and ''b -> 'a'
,它編譯正確:
let apply fr xr =
match fr, xr with
| Success f, Success x -> Success (f x)
| Failure a, Success _ -> Failure a
| Success _, Failure b -> Failure b
| Failure a, Failure b -> Failure (List.concat [a; b])
爲什麼使用匹配的超值(這裏是fr或xr)無法正常工作,但構建新的失敗值呢?
謝謝約翰。目前還不清楚爲什麼第一場比賽可以替代 '| |成功f,成功x - >成功(f x)' 應該對第二場比賽有任何影響 '| |失敗_,成功_ - > fr' 對我來說聽起來像編譯器中不必要的限制... – dumetrulo
問題是'fr'與'Success(fx)'具有不同的類型,並且表達式需要返回變量相同的類型。 –