f# - 寓言 - 无法获取泛型参数的类型信息,请内联或注入类型解析器
问题描述
我正在尝试在寓言中编写一个通用的 json 解码函数。它似乎在 FSharp 中编译,但我收到此代码的错误消息:
[使用来自 Fable.PowerPack 的 Thoth.Json 库和 Fetch 库]
let autoDecoder<'a> (json:string) (value:obj) : Result<'a, Thoth.Json.Decode.DecoderError> =
let tryDecode = Thoth.Json.Decode.Auto.fromString<'a>(json)
let getDecoderError (str:string) : Thoth.Json.Decode.DecoderError = ( "Auto decode Error", Thoth.Json.Decode.FailMessage str)
Result.mapError getDecoderError tryDecode
错误寓言:无法获取泛型参数的类型信息,请内联或注入类型解析器
我不知道如何解决这个问题,也无法在谷歌上找到任何东西。
我希望能够在 Fable Elmish 的更新函数中调用这样的函数:
let update (msg:Msg) (model:Model) =
match msg with
..
| OrStart ->
let getData() = Fetch.fetchAs<ResultResponse> "https://randomuser.me/api/" json.autoDecoder<ResultResponse> http.getHeaders
model, Cmd.ofPromise getData () LoadedTypedData FetchError
我怎样才能获得寓言来编译 autoDecoder<'a> 函数,同时保持它的通用性?
谢谢
解决方案
我认为 Fable 是在告诉你这样使用inline
:
let inline autoDecoder<'a> (json:string) (value:obj) : Result<'a, Thoth.Json.Decode.DecoderError> =
let tryDecode = Thoth.Json.Decode.Auto.fromString<'a>(json)
let getDecoderError (str:string) : Thoth.Json.Decode.DecoderError = ( "Auto decode Error", Thoth.Json.Decode.FailMessage str)
Result.mapError getDecoderError tryDecode
这是因为像内联函数一样的泛型函数需要为每个调用实例化。
顺便说一句,该value
参数未被使用。
您还可以像这样简化代码:
let inline autoDecoder<'a> (json:string) : Result<'a, Thoth.Json.Decode.DecoderError> =
Thoth.Json.Decode.Auto.fromString<'a> json
|> Result.mapError (fun (str:string) -> "Auto decode Error", Thoth.Json.Decode.FailMessage str)
推荐阅读
- system.diagnostics - Process.WaitForExit(n) 不会在 Process.Start() 之后立即等待
- c# - 从“MetroListView”获取选定的项目文本
- javascript - 将对象数组传递给 ReactJS 中的子组件,但第一个返回它是未定义的并破坏了代码
- python - 简单的 ray python 示例无法使其并行执行
- elasticsearch - bool 格式错误的查询,应为 END_OBJECT,但发现 FIELD_NAME 无法查询 _search
- javascript - 需要帮助从对象数组制作数字列表
- elasticsearch - 聚合最新的嵌套值
- xmpp - stanzajs 向群聊发送简单的消息
- javascript - 嵌套的 setTimeout 在 js 中无法正常工作
- c# - 为什么 CPU-Bound 代码锁定 GUI 在 async \ await 与 IO-Bound 不同?