【发布时间】:2011-04-27 20:29:21
【问题描述】:
经常有人告诉我,使用 OCaml 中的 Lazy 模块,可以使用诸如 Haskell 之类的惰性语言完成所有您可以做的事情。为了测试这种说法,我正在尝试编写一个函数,将常规列表转换为 ocaml 中的静态双向链表。
type 'a dlist = Dnil | Dnode of 'a dlist * 'a * 'a dlist
鉴于这种类型,我可以手动创建几个静态双向链表:
let rec l1 = Dnode (Dnil,1,l2)
and l2 = Dnode (l1,2,l3)
and l3 = Dnode (l2,3,Dnil)
但我想编写一个'a list -> 'a dlist 类型的函数,给定任何列表都会在 OCaml 中构建一个静态双向链表。例如,给定[1;2;3],它应该输出与上面的l1 等效的内容。
用 Haskell 编写算法非常简单:
data DList a = Dnil | Dnode (DList a) a (DList a)
toDList :: [a] -> DList a
toDList l = go Dnil l
where
go _ [] = Dnil
go h (x:xs) = let r = Dnode h x (go r xs) in r
但我无法弄清楚在哪里调用 lazy 以使其在 OCaml 中编译。
【问题讨论】:
-
首先,类型是
'a dlist,而不是'a DList。 ;)
标签: ocaml lazy-evaluation