Scala向量折叠语法(/:和:\和/:\) [英] Scala Vector fold syntax (/: and :\ and /:\)

查看:116
本文介绍了Scala向量折叠语法(/:和:\和/:\)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供一些示例方法

Can someone provide some examples for how

/: :\/:\

实际上习惯了吗?我认为它们是reduce/fold方法的快捷方式,但是没有关于如何在Scala文档中实际使用它们的示例,并且不可能在StackOverflow上进行Google搜索.

Actually get used? I assume they're shortcuts to the reduce / fold methods, but there's no examples on how they actually get used in the Scala docs, and they're impossible to google / search for on StackOverflow.

推荐答案

/:foldLeft的同义词,而:\foldRight的同义词.

/: is a synonym for foldLeft and :\ for foldRight.

但是请记住,:使/:应用于其右侧的对象.

But remember that : makes /: apply to the object to the right of it.

假设您知道(_ * _)是等效于(a, b) => a * b的匿名函数,并且foldLeft和foldRight的签名为

Assuming you know that (_ * _) is an anonymous function that's equivalent to (a, b) => a * b, and the signature of foldLeft and foldRight are

def foldLeft  [B] (z: B)(f: (B, A) ⇒ B): B 
def foldRight [B] (z: B)(f: (A, B) ⇒ B): B 

即它们是带有初始值的咖喱函数,以及将初始值/累加器与列表中的一项组合在一起的函数,例如:

i.e. they're curried functions taking a start value and a function combining the start value / accumulator with an item from the list, some examples are:

List(1,2,3).foldLeft(1)(_*_)

(1 /: List(1,2,3))(_*_)

还有

List(1,2,3).foldRight(1)(_*_)

中缀表示法是

(List(1,2,3) foldRight 1)(_*_)

(List(1,2,3) :\ 1)(_*_)

添加您自己的收藏和功能并享受!

Add your own collections and functions and enjoy!

使用短(/::\)表示法要记住的事情是,因为您使用的是中缀表示法,因此需要在第一部分的前面加上括号,以便它能够选择第二个参数.正确列出.另外,请记住,foldLeft和foldRight的功能是相反的,但是如果您可视化头部中的折叠,这是有道理的.

The thing to remember with the short (/: and :\) notations is that, because you're using the infix notations you need to put parentheses around the first part in order for it to pick up the second argument list properly. Also, remember that the functions for foldLeft and foldRight are the opposite way round, but it makes sense if you're visualising the fold in your head.

这篇关于Scala向量折叠语法(/:和:\和/:\)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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