为什么foldBack的签名与F#中的fold如此不同? [英] Why is the signature of foldBack so much different from fold in F#?

查看:68
本文介绍了为什么foldBack的签名与F#中的fold如此不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

至少我不了解两件事:

  • 从左侧折叠到右侧折叠的重构不仅需要在签名上进行很多更改,而且在每个地方都取决于文件夹功能
  • 没有翻转参数就无法将其与列表链接

List.foldBack : ('T -> 'State -> 'State) -> 'T list -> 'State -> 'State

List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State

为什么有人会把所有参数都放在foldBack签名中而不是fold上呢?

Any good reason for why would someone put all parameters in reverse in the signature of foldBack compared to fold?

推荐答案

它只是一个有用的助记符,可帮助程序员记住列表的迭代方式.想象一下,您的列表的布局以左边的开头和右边的结尾为准. fold从左侧的初始状态开始,向右累积状态. foldBack与此相反,它从右侧的初始状态开始,然后返回到左侧的列表.

It's just a useful mnemonic to help the programmer remember how the list is iterated. Imagine your list is laid out with the beginning on the left and the end on the right. fold starts with an initial state on the left and accumulates state going to right. foldBack does the opposite, it starts with an initial state on the right and goes back over the list to the left.

这肯定显示了F#的OCaml传统,因为其他一些功能语言(Haskell,Scala,ML)将列表保留为最后一个参数,以允许使用更常见的部分应用程序场景.

This is definitely showing F#'s OCaml heritage as some other functional languages (Haskell, Scala, ML) keep the list as the last argument to allow for the more common partial application scenarios.

如果我真的需要一个与fold完全相似的foldBack版本,则可以定义自己的帮助函数:

If I really needed a version of foldBack that looked exactly like fold, I would define my own helper function:

module List = 
  let foldBack' f acc lst =
    let flip f a b = f b a
    List.foldBack (flip f) lst acc

这篇关于为什么foldBack的签名与F#中的fold如此不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆