问题描述
我有以下Scala代码示例,我想知道为什么我在foldLeft上收到错误,但是没有使用foldRight?
val xs =列表(1,2,3)
val ys =列表(4,5,6)
(xs foldLeft ys)(_ :: _)//错误:Value ::不是Int
(xs foldRight ys)(_ :: _)// Res:List(1 ,2,3,4,5,6)
我是Scala新手,所以请回复尽可能简单。感谢
将运算符(函数)的参数传递给 foldLeft
和 foldRight
是相反的。
所以在 foldLeft
您的 _ :: _
以 ys :: xs.head
开头,没有任何意义。 / p>
使用 foldRight
,最内层的操作是 xs.last :: ys
,这是很好的。
参数顺序在运算符版本中更有意义: z /:ws
ws (即 foldLeft
)推送 z
而 ws:\ z
向左推动 z
(即 foldRight
)。而且参数的顺序与 z
与 w
的顺序一致。
I have following Scala code sample and I want to know why I get an Error on foldLeft but not with foldRight?
val xs = List(1,2,3)
val ys = List(4,5,6)
(xs foldLeft ys) (_::_) // Error: Value :: is not a member of Int
(xs foldRight ys) (_::_) // Res: List(1, 2, 3, 4, 5, 6)
I am new to Scala, so please reply as simple as you can. Thanks
The arguments for the operator (function) passed to foldLeft
and foldRight
are in opposite order.
So in foldLeft
your _ :: _
starts with ys :: xs.head
, which doesn't make any sense.
With foldRight
, the innermost operation is xs.last :: ys
, which is fine.
The argument order makes more sense in the operator versions: z /: ws
pushes z
righward through ws
(i.e. foldLeft
), while ws :\ z
pushes z
leftward (i.e. foldRight
). And the order of arguments inside agrees with the order of z
vs. w
above.
这篇关于Scala:Value ::不是Int的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!