gpt4 book ai didi

f# - 错误 FS0001,此函数应具有类型 byref

转载 作者:行者123 更新时间:2023-12-05 00:19:35 25 4
gpt4 key购买 nike

我做了一个简单的函数,它包装了签名 'a -> 'b -> 'c option 的常见 F# 函数更多“符合 C#”的功能为:'a -> b -> byref<'c> -> bool .但不知何故,当我尝试将这样的方法包装在一个类中时,我得到了错误 FS0001 并且我找不到错误。

下面的代码

open System
open System.Runtime.InteropServices

// Given a function, f: 'a -> 'b -> 'c option returns
// A new function g: 'a -> 'b -> byref<'c> -> bool
let wrapOptionF f a b (g:byref<'c>) =
match f a b with
| Some v ->
do g <- v
true
| None ->
false

let tryDivide (a:int) (b:int) =
match Math.DivRem(a,b) with
| v, 0 -> Some v
| _ -> None

type TryDivideWrapper() =
static member TryDivide(a, b, [<Out>]cRef:byref<int>) : bool =
let f = wrapOptionF tryDivide a b
f cRef

违规行是 f cRef .

最佳答案

This post包含更深入的解释,但简而言之,您可以将最终类型定义替换为以下内容:

type TryDivideWrapper() =
static member TryDivide(a, b, [<Out>]cRef:byref<int>) : bool =
wrapOptionF tryDivide a b &cRef

原因是您的 wrapOptionF需要 byref范围。但是, byref<int>不是真正的类型 intint ref - 这只是向编译器指示您的参数应通过引用传递(如 C# 中的 out)。然而,一旦进入你的函数,你所拥有的是一个普通的 int。 .

编辑:请注意,Intellisense 将显示 cRef具有类型 byRef<int> .但是,如果将另一个变量绑定(bind)到 cRef , 你会看到你得到的类型是一个普通的 int .您可以将此行放入 TryDivide然后将鼠标悬停在 a看见了:
let a = cRef

使用 &运算符告诉编译器您正在传递 cRef进入 f通过引用 - 这正是 f需求 - 使类型系统满意。我已经使用 C# 项目对此进行了测试,并且 TryDivideWrapper.TryDivide(a, b, out c)按预期工作。添加@MarkSeemann 的 tryDivide你应该很高兴。

关于f# - 错误 FS0001,此函数应具有类型 byref<int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com