我有一个大块let
,可以处理大量计算,并且我试图通过将其大块分解为函数来将其分解为较小的块。我需要将对打开的对象进行操作的函数传递给这些组件,并在下面的简化代码中最好地表达出烦恼:
type 'a foo = 'a
constraint 'a = < bar: string option; .. >
type foo' = < bar: string option; >
type bar = < bar: int option; qux: int option >
type ('a, 'b) fn = 'a foo -> 'b foo
let a = object method bar = None method qux = None end
let b = object method bar = None end
(* Doesn't work *)
let xyz fn =
let res = fn a in
let res' = fn b in
res, res'
(* Doesn't work *)
let xyz (fn:('a, 'b) fn) =
let res = fn a in
let res' = fn b in
res, res'
(* Doesn't work *)
type fn' = foo' -> foo'
let xyz (fn:fn') =
let res = fn a in
let res' = fn b in
res, res'
(* Sub-par solution: imagine needing several of these conversions across several
functions, which is the situation I have when trying to decompose a large let
block into component functions like xyz. *)
let xyz (fn:('a, 'b) fn) =
let res = fn (a :> foo') in
let res' = fn b in
res, res'
(* Another sub-par solution: *)
type ('a, 'b) fn'' = { fn: 'a. 'a foo -> 'b foo }
let xyz (fn:('a, 'b) fn'') =
let fn = fn.fn in
let res = fn a in
let res' = fn b in
res, res'
(* What I want: *)
type ('a, 'b) fn''' = 'a. 'a foo -> 'b foo
let xyz (fn:('a, 'b) fn''') =
let res = fn a in
let res' = fn b in
res, res'
(* What I am currently using (don't pass the function around to HOFs: keep the
computation all in a massive let statement. *)
let _ =
let a : foo = object method bar = None method qux = None end in
let b : bar = object method bar = None end in
let fn a = object method bar = a#bar method qux = None end in
(* fn gets the correctly inferred type of < bar : 'a; .. > -> < bar : 'a; qux : 'b option > *)
fn a, fn b
任何指导,或关于为什么我想要的东西的任何指导,都是不可能/无法保证的,现在或将来确实有希望,在一个光明的世界中,这将是可行的,这一点将不胜感激。
您想要的是在定义内多态使用函数参数:即,将fn
应用于两个不同对象类型的值xyz
。这称为Rank-2多态性(https://wiki.haskell.org/Rank-N_types),但在Hindley Milner类型系统中不受支持(它只能处理Rank-1)。OCaml基于Hindley Milner,也不直接支持Rank-N。
当前,OCaml对Rank-2多态性的支持非常间接:通过多态记录成员进行模拟,而无需任何类型推断。我想您的“另一种低于标准价格的解决方案”是这里的最佳方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句