Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 列表的自定义反转函数_Scala_Functional Programming - Fatal编程技术网

Scala 列表的自定义反转函数

Scala 列表的自定义反转函数,scala,functional-programming,Scala,Functional Programming,我是scala新手,希望以函数式的方式实现一个通用的反向函数。我想要以下格式的函数 def customReverse[T](list: List[T]) : List[T] ={ // not implemented yet } 提前感谢 您可以尝试以下方法 def customReverse[T](list: List[T]) : List[T] ={ list match{ case Nil => Nil case x :: xs => customReverse(xs

我是scala新手,希望以函数式的方式实现一个通用的反向函数。我想要以下格式的函数

def customReverse[T](list: List[T]) : List[T] ={
// not implemented yet
}

提前感谢

您可以尝试以下方法

def customReverse[T](list: List[T]) : List[T] ={
 list match{
 case Nil => Nil
 case x :: xs => customReverse(xs) :+ x
 }
}
调用函数
customReverse(List(1,2,3,4))
时,您将得到一个输出

List(4,3,2,1)

通过折叠可以很容易地进行反转

def customReverse[T](list: List[T]): List[T] =
  list.foldLeft[List[T]](Nil) { (a, b) => b :: a }
foldLeft
在列表中的每对元素之间放置一个二进制操作。因此,如果我们给我们的函数
{(a,b)=>b::a}
一个名称,
(使用中缀名称在进行这些缩减时会使一切看起来更漂亮),左折看起来像这样(当然是伪代码)

customReverse(列表(1,2,3))
列表(1,2,3).foldLeft(无)()
((无1)2)3)
((列表(1)2)3)
(列表(2,1)3)
清单(3、2、1)

您遇到问题的代码是什么?你的代码有什么问题?你收到错误信息了吗?如果是,它说什么,它发生在哪一行?你得到的结果不是你期望的结果吗?如果是,你期望得到什么样的结果?为什么你期望得到这个结果?你得到了什么样的结果?为什么这个结果不是正确的?你正在观察的行为不是你期望的行为吗?如果是的话,你期望什么样的行为,为什么你期望它,你会观察到什么样的行为,为什么这种行为不是正确的?不是一个代码编写服务(那些确实存在,他们被称为“程序员”,你可以雇佣他们),你需要付出一些努力。请阅读并学习如何在二次时间内构造一个反向链表,真的吗?
customReverse(List(1, 2, 3))
List(1, 2, 3).foldLeft(Nil)(<>)
(((Nil <> 1) <> 2) <> 3)
((List(1) <> 2) <> 3)
(List(2, 1) <> 3)
List(3, 2, 1)