SML:调用自身另一个实例的多态函数

SML: Polymorphic function that calls another instantiation of itself

有没有办法编写一个多态函数(在 sml 中),它使用与它所获得的参数类型不同的参数调用自身?

例如,我正在查看 this answer,(它有声明 datatype ('a,'b)alterlist = Nil| element of 'a*('b,'a)alterlist;)并且直觉上,我想实现函数 unzip,如:

fun unzip Nil = ([],[]) |
    unzip (element(x,l)) = let val (b,a)=unzip l in (x::a,b) end;

类型推断系统将其理解为 ('a,'a) alterlist -> 'a list * 'a list,但我想要 ('a,'b) alterlist -> 'a list * 'b list 类型的东西(以便内部调用是 ('b,'a) alterlist -> 'b list * 'a list

我相信您要求的是 polymorphic recursion,它没有在标准 ML 中实现。

然而,这是在 Haskell 中实现的(正如@seanmcl 指出的那样,ocaml):

import Prelude hiding(unzip)

data Alterlist a b = Nil | Elem a (Alterlist b a)

unzip :: Alterlist a b -> ([a], [b])
unzip Nil = ([], [])
unzip (Elem x l) =
    let (b, a) = unzip l
    in (x : a, b)

x = Elem 1 (Elem True (Elem 5 (Elem False Nil)))

*Main> unzip x
([1,5],[True,False])