【问题标题】:SML: Polymorphic function that calls another instantiation of itselfSML:调用自身另一个实例化的多态函数
【发布时间】:2015-12-07 03:37:41
【问题描述】:

有没有办法编写一个多态函数(在 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

【问题讨论】:

    标签: recursion polymorphism sml


    【解决方案1】:

    我相信您要的是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])
    

    【讨论】:

    • ocaml 也支持多态递归
    猜你喜欢
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2016-11-16
    相关资源
    最近更新 更多