gpt4 book ai didi

haskell - 扩大 ocaml 中的类型

转载 作者:行者123 更新时间:2023-12-03 22:16:02 26 4
gpt4 key购买 nike

我正在尝试用 ocaml 编写一个免费的 monad 库,关注 Control.Monad.Free来自haskell,但我在执行hoistFree 时陷入了困境。

hoistFree :: Functor g => (forall a. f a -> g a) -> Free f b -> Free g b
hoistFree _ (Pure a) = Pure a
hoistFree f (Free as) = Free (hoistFree f <$> f as)

这是我的翻译尝试。

let rec hoistfree : 'b.('b t -> 'b t) -> 'a m -> 'a m =
fun f x -> match x with
| Return x -> Return x
| Free x -> Free (T.map (hoistfree f) (f x));;

不幸的是,我收到一个错误,告诉我我没有正确扩大 g 的类型。

Error: This definition has type ('b m t -> 'b m t) -> 'b m -> 'b m
which is less general than 'a. ('a t -> 'a t) -> 'b m -> 'b m

如果我不插入函数类型注释,一切正常,但是正如错误消息所说,我没有得到 f 的一般类型。
问题出在哪儿?如何扩大 f 的类型?

最佳答案

我对 Ocaml 不是很熟悉,但我相信

let rec hoistfree : 'b.('b t -> 'b t) -> 'a m -> 'a m =

被解析为

let rec hoistfree : 'b. ( ('b t -> 'b t) -> 'a m -> 'a m ) =

代替

let rec hoistfree : ('b. ('b t -> 'b t)) -> 'a m -> 'a m =

前者是基本的多态类型,后者是 rank2 类型,比 Hindley-Milner 需要更多类型系统的支持。

IIRC,要实现后者,您需要定义自定义包装器数据类型。例如:

type poly = { polyf: 'a . 'a -> 'a } ;;

let foo (x: poly): int = x.polyf 4;;
let bar: poly = { polyf = fun x -> x } ;;

let _ = print_string ("hello " ^ string_of_int (foo bar));;

关于haskell - 扩大 ocaml 中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39426861/

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