该标准 ML 代码到底有什么作用?
我正在阅读 Chris Okasaki 的纯函数式数据结构,其中有一个示例我遇到了麻烦。它位于此处。特别是,我不明白 rotate
和 exec
函数是如何工作的:
fun rotate($Nil, y::_, a) = $Cons (y, a)
| rotate ($Cons (x, xs), y :: ys, a) =
$Cons(x, rotate (xs, ys, $Cons (y, a)))
fun exec (f, r, $Cons (X, s)) = (f, r, s)
| exec (f, r, $Nil) = let val f' = rotate (f, r, $Nil) in (f', [], f') end
有人可以用愚蠢的术语来解释吗?我仍在学习基于机器学习的语言。 :-)
I'm reading Chris Okasaki's purely functional data structures, and there's one example I am having trouble with. It is located here. In particular, I don't understand how the rotate
and exec
functions work:
fun rotate($Nil, y::_, a) = $Cons (y, a)
| rotate ($Cons (x, xs), y :: ys, a) =
$Cons(x, rotate (xs, ys, $Cons (y, a)))
fun exec (f, r, $Cons (X, s)) = (f, r, s)
| exec (f, r, $Nil) = let val f' = rotate (f, r, $Nil) in (f', [], f') end
Could someone put this in stupid-people terms? I'm still learning my ML-based languages. :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这看起来不像我学过的标准机器学习(在数据构造函数前面有 $ 字符),但也许事情已经改变了。不管怎样:
首先,rotate的第2行有一个小错字,你在
$Cons
后面添加了一个逗号。基本上rotate接受三个列表的元组并按顺序组装它们:第一个++(反向第二个)++ 第三个。但它通过同时从列表 1 和列表 2 中提取元素来线性地完成此操作。列表 1 的头部与最终结果一致(ao(1) 操作)。但是列表 2 的尾部作为参数传递给递归调用,并且其头部被 cons 到第三个参数上,这相当于将其反转。
第三个参数基本上充当累加器。在函数式编程中,使用累加器作为参数可能是避免更昂贵的计算的一个技巧。
我承认不理解exec的目的。背景是什么?
That doesn't look like the Standard ML I learned (with $ characters in front of data constructors) but perhaps things have changed. Anyhow:
First of all there's a small typo on line 2 of rotate, you added a comma after
$Cons
Basically rotate takes a tuple of three lists and assembles them in the order: first one ++ (reverse of second one) ++ third one. But it does this linearly by pulling elements from both list 1 and list 2 at the same time. The head of List 1 is cons'd to the final result (a o(1) operation). But the tail of list 2 is passed as an argument to the recursive call, and its head is cons'd onto the third argument, which amounts to reversing it.
That third argument is basically acting as an accumulator. In functional programming using an accumulator as an argument like that can be a trick for avoiding more expensive computations.
I admit to not understanding the purpose of exec. What's the context?
这并不能解释整个事情,但请注意,在
funrotate($Nil, y::_, a)
中,y::_
是一种模式,匹配一个列表,其中列表的头部(第一个元素)标记为y
,列表的尾部(第一个元素之后的每个项目)标记为_
。_
充当通配符模式。查看 Wikipedia 上的 SML,特别是 Mergesort 实现,了解
的更多使用::
模式和_
。This doesn't explain the whole thing, but note that in
fun rotate($Nil, y::_, a)
, they::_
is a pattern that matches a list wherein you label the head of the list (first element) asy
and the tail of the list (every item after the first element) as_
._
acts as a wildcard pattern.Check out SML on Wikipedia, specifically the Mergesort implementation, for more use of
::
patterns and_
.